0
votes

I have a dataset in the following format

value1 value2 group
10 20 A
20 30 A
67 45 B
98 76 C
102 11 A
11 22 B
10 10 B
19 20 C

I am trying to make box plots for three groups (A, B and C) and the box plots for 1st and end column should be side by side. I can do two separate plots like following, but not able to figure out how to combine to put it side by side.

p1 <- ggplot(x, aes(x=group, y=value1)) + geom_boxplot()
p2 <- ggplot(x, aes(x=group, y=value)) + geom_boxplot()

I would appreciate any help. I am a newbie in R and ggplot.

2
Does this answer your question? Side-by-side plots with ggplot2 - user438383
I would suggest to reshape to long format like so: xx <- tidyr::pivot_longer(x, -group) ggplot(xx, aes(x=group, y=value, color = name)) + geom_boxplot() - stefan
Thanks @stefan !! It works great as it makes box plots for all columns which was also one of the requirements. - SBDK8219

2 Answers

1
votes

Here's an option using pivot_longer from tidyr

x_new <- tidyr::pivot_longer(x, c(value1, value2))

ggplot(x_new, aes(x = group, y = value, col = name, fill = name)) + geom_boxplot(alpha = .5)
0
votes

The gridExtra package can do this too. Assign your plots to variables then just use grid.arrange(plot1,plot2). Look up the documentation with ?grid.arrange for extra options.