0

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.

SBDK8219
  • 661
  • 4
  • 11
  • Does this answer your question? [Side-by-side plots with ggplot2](https://stackoverflow.com/questions/1249548/side-by-side-plots-with-ggplot2) – user438383 May 28 '21 at 22:57
  • 2
    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 May 28 '21 at 23:03
  • Thanks @stefan !! It works great as it makes box plots for all columns which was also one of the requirements. – SBDK8219 May 29 '21 at 03:34

2 Answers2

2

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)
ltr
  • 332
  • 2
  • 9
  • Thanks !! It works fine as well as @stefan's solution. I appreciate both of your help. – SBDK8219 May 29 '21 at 03:36
  • I'd appreciate it if you could accept the answer. I hadn't noticed @stefan had already proposed pretty much the same method in a comment. If they copy that into an answer feel free to accept that one as they came first. – ltr Jun 01 '21 at 04:26
  • I am sorry!! I clicked the "UP" button instead of accepting answer. I just accepted . Thanks again. – SBDK8219 Jun 03 '21 at 15:50
0

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.

zeejay
  • 11
  • 2