Home > Enterprise >  r - ggplot2 barplot of binary data
r - ggplot2 barplot of binary data

Time:07-22

I've a column of a dataset like : [1, 2, 1, 1, 1, 1, 2, 2, ...] where 1 is male and 2 female.

What I want is to create a plot like the one in the pictures but I couldn't.

  ggplot( aes(x=age))  
    geom_density(fill="#69b3a2", color="#e9ecef", alpha=0.8)

I don't know how to put instead of the range [-0.5, 0.5] for male, indicates male, and [0.5, 1.5] female.

An example of what I want - a bar plot with counts for female and male

CodePudding user response:

The x-axis is a numeric value because you are passing a numeric vector. Converting it to a character vector is probably the easiest approach.

library(ggplot2)
library(dplyr)

# Original data
df <- data.frame(gender = c(1, 2, 1, 1, 1, 1, 2, 2))

# Convert to character
df <- df %>% mutate(Gender = case_when(gender == 1 ~ "Male",
                                 gender == 2 ~ "Female"))
# Plot
ggplot(df, aes(x = gender))  
  geom_bar()   
  ggtitle("Gender")

  • Related