0

My plot has two problems:

(1) the group bars are not ordered as I want them to be - I will like them to appear in the order entered and (2) for the legend, the order appears as V, E, B whereas in the groups, it appears as B, E, V. I can reverse the legend, however, what I will really like to get is change the order of the subplots to V, E, B.

library(ggplot2)

df2 <- data.frame(supp = rep(c("V","E","B"), each=5),
                  s = rep(c("C3","C1", "C2","C5","C6"), 3),
                  len = c(1,2,3,4,5,6,8,4,4,3,9,7,6,8,5))

p <- ggplot(data = df2, aes(x = s, y = len, fill = supp)) + 
       geom_bar(stat = "identity", color = "black", position = position_dodge())

p + scale_fill_brewer(palette = "Blues", guide = guide_legend(reverse = TRUE)) +
      scale_x_discrete(limits = rev(levels(df2$s))) 
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51

2 Answers2

2

You need to change df2$supp from character to factor and specify the levels as you want them to appear.

See modified code below. Also, check out this link for even more detail about how to control the colour of your variables so they are consistent.

library(ggplot2)

df2 <- data.frame(supp = rep(c("V","E","B"), each=5),
                  s = rep(c("C3","C1", "C2","C5","C6"), 3),
                  len = c(1,2,3,4,5,6,8,4,4,3,9,7,6,8,5))

df2$supp <- factor(df2$supp,
                   levels = c("V", "E", "B"))

p <- ggplot(data=df2, aes(x=(df2$s), y=len, fill=supp)) + 
  geom_bar(stat="identity", color="black", position=position_dodge())

p + scale_fill_brewer(palette="Blues", guide = guide_legend(reverse=TRUE)) +
  scale_x_discrete(limits = rev(levels(df2$s))) 

enter image description here

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Prevost
  • 677
  • 5
  • 20
  • I edit your answer by adding a plot of output to make it more clear. You can check whether it's created by your code. Hope that I don't offend you. – Darren Tsai Feb 02 '19 at 05:27
  • That’s a good point. That would have been helpful in my answer and I will use it for the future! No offence taken here! – Prevost Feb 02 '19 at 21:07
0

Data

df2 <- data.frame(supp = rep(c("V", "E", "B"), each = 5),
                  s = rep(c("C3", "C1", "C2", "C5", "C6"), 3),
                  len = c(1, 2, 3, 4, 5, 6, 8, 4, 4, 3, 9, 7, 6, 8, 5))

Adjustment

Because you use data.frame() to create data, R will set strings as factors by default. So you need to revise the types of variables to what you want.

df2$s <- as.character(df2$s)
df2$supp <- factor(df2$supp, levels = c("V", "E", "B"))

Plot

ggplot(data = df2, aes(x = s, y = len, fill = supp)) + 
  geom_bar(stat = "identity", color = "black", position = position_dodge()) +
  scale_fill_brewer(palette = "Blues", direction = -1)

Here you don't need to use additional guide_legend() and scale_x_discrete() to change order. It will be more concise.

enter image description here

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51