how to put two variables boxplot on a same categorical variable in ggplot in r

To put two variable boxplots on the same categorical variable using ggplot in R, you can use the aes() function to specify the aesthetic mappings, and the geom_boxplot() function to create the boxplots.

Here is an example code:

main.r
library(ggplot2)

# create sample data
dat <- data.frame(
  category = rep(c("A", "B", "C"), each = 100),
  variable1 = rnorm(300, 50, 10),
  variable2 = rnorm(300, 70, 15)
)

# plot boxplots with two variables 
ggplot(dat, aes(x = category, y = variable1)) +
  geom_boxplot(aes(fill = "variable1")) +
  geom_boxplot(aes(x = category, y = variable2, fill = "variable2"),
               position = position_dodge(width = 0.75)) +
  scale_fill_manual(values = c("variable1" = "blue", "variable2" = "red")) +
  labs(x = "Category", y = "Value", fill = "Variable") +
  theme_classic()
581 chars
18 lines

In this example, we create a sample dataset with a categorical variable "category", and two variables "variable1" and "variable2". Then, we use ggplot() to create a plot, and specify the x-axis as the categorical variable "category" using aes(x = category). We also specify the first variable "variable1" on the y-axis using aes(y = variable1), and create a blue boxplot using geom_boxplot(aes(fill = "variable1")).

For the second variable "variable2", we use geom_boxplot() again with aes(x = category, y = variable2, fill = "variable2") to specify the second variable on the y-axis, and create a red boxplot using scale_fill_manual(values = c("variable1" = "blue", "variable2" = "red")).

We also use position_dodge(width = 0.75) to dodge the two boxplots side by side for better visualization. Finally, we add axis labels and themes using labs() and theme_classic().

gistlibby LogSnag