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.r581 chars18 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