Home > Blockchain >  When plotting dummy variables, how can I change the 0.0,1.0 on x-axis into male female?
When plotting dummy variables, how can I change the 0.0,1.0 on x-axis into male female?

Time:11-13

I am using ggplot2 to make a barplot. X-axis is a dummy variable so it shows 0.0 and 1.0 on the plot. But I want to make it more readable. For example, change the 0.0 to male, 1.0 to female.

CodePudding user response:

The easier way is to mutate the data frame column from numeric to factor type prior the plotting. See the code below:

library(tidyverse)

# Simulation
df <- data.frame(gender = c(0, 0, 1, 1, 0, 0), country = factor(c("US", "EU", "UK", "US", "EU", "EU")))


# Mutate from numeric to factor
df_m <- df %>% as_tibble() %>%
  mutate(gender = as.factor(if_else(gender < 1, "Male", "Female")))

# Plots
ggplot(df_m, aes(gender, fill = country))  
  geom_bar()

Output: barplot

  • Related