0

I have a data frame similar to this one:

year LE  Rn
2005 400 500
2006 402 501
2007 403 502
2008 404 503
2009 405 504
2010 406 503

and now I would like to have a box plot with year on x-axis and water equivalents (mm) on y-axis and then LE an Rn per year next to each other.

I've tried:

ggplot(df, aes(x=as.factor(df$year),y=df$LE, fill=df$Rn)) +
         geom_bar(stat="identity",fill="steelblue", position = position_dodge())

but it only plots only the LE and not the Rn.

Thank you!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214

1 Answers1

2

You will need to reflow your data to a "long" format. This means that the variables you want to have dodged will have to appear in the same column. Also, notice how I refer to values within aes. You should too.

library(ggplot2)
library(tidyr)

xy <- read.table(text = "year LE  Rn
2005 400 500
2006 402 501
2007 403 502
2008 404 503
2009 405 504
2010 406 503", header = TRUE)

xy <- gather(xy, key = stats, value = value, -year)

# Notice how values are now in "long" format.
> head(xy)
  year stats value
1 2005    LE   400
2 2006    LE   402
3 2007    LE   403
4 2008    LE   404
5 2009    LE   405
6 2010    LE   406
> tail(xy)
   year stats value
7  2005    Rn   500
8  2006    Rn   501
9  2007    Rn   502
10 2008    Rn   503
11 2009    Rn   504
12 2010    Rn   503

ggplot(xy, aes(x = as.factor(year), y = value, fill = stats)) +
  theme_bw() +
  scale_fill_brewer(palette = "Set1") +
  geom_bar(stat = "identity", position = position_dodge())

enter image description here

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197