[R] Legend / bar order - ggplot2

Yang Lu Yang.Lu at williams.edu
Mon Aug 29 15:18:08 CEST 2011


Hi all,

I am trying to do a barplot in ggplot2 and want to make sure that the legend order is consistent with the bar order, that is the legend order is orig and match; and the bars are ordered in the same way. It seems to me that I can only control one of them. Any idea?

library(ggplot2)
df <- data.frame(value = rnorm(20),
                 name = factor(rep(letters[1:10], 2), levels = letters[1:10]),
                 type = factor(c(rep("orig", 10),
                   rep("match", 10)), levels = c("orig", "match")))

ggplot(df, aes(x = name, y = value, fill = type)) +
  geom_bar(position = position_dodge()) +
  coord_flip()

Thank you very much,

YL



More information about the R-help mailing list