John Chandler
John Chandler

Reputation: 3

legend does not follow ordered bars in R

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))) 

Upvotes: 0

Views: 81

Answers (2)

Darren Tsai
Darren Tsai

Reputation: 35554

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

Upvotes: 0

Prevost
Prevost

Reputation: 697

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

Upvotes: 2

Related Questions