Search code examples
rggplot2geom-text

Labels are out of order (ggplot2)


When I add labels to my plot, they are in the wrong order. I want to rearrange the LABELS, not the bars themselves. Sample code:

df = data.frame(A = c("Apples", "Apples", "Apples", "Apples", "Apples", "Apples",
                      "Oranges", "Oranges", "Oranges", "Oranges", "Oranges", "Oranges"),
                B = c("Red", "Green", "Red", "Green", "Red", "Green",
                      "Red", "Green", "Red", "Green", "Red", "Green"),
                C = c(3, 4, 2, 3, 4, 6, 2, 2, 3, 8, 8, 6))

library(tidyverse)

df.summary = df %>%
  group_by(A, B) %>%
  summarise(new = list(mean_se(C))) %>%
  unnest(new)
df.summary$B <- factor(df.summary$B, levels = c("Red", "Green"))

df.labels = c(1, 2, 3, 4)

ggplot(df.summary, aes(x = A, y = y, fill = factor(B))) +
  geom_bar(stat = "identity", position = position_dodge(.95)) +
  geom_errorbar(aes(ymin = ymin, ymax = ymax, width = 0.5), 
                position = position_dodge(.95)) +
  geom_text(position = position_dodge(width = 1), size = 6, 
            label = df.labels, hjust = .5, vjust = 0, angle = 0)

And we get:

Bar plot with incorrect label order (2-1-4-3 instead of 1-2-3-4):

enter image description here

Refactoring the data in different ways does not change the labels. I can't get them in the right order no matter what I try. I'm assuming it's a problem with geom_text but I can't for the life of me figure it out.

What's going on?


Solution

  • Does this help? It is presumed(assumed?) that A and B are factors.

     library(tidyverse)
        df.summary$A<-fct_reorder(df.summary$A,df.labels)
        df.summary$B<-fct_reorder(df.summary$B,df.labels)
        ggplot(df.summary, aes(x=A, y=y, fill=B))+
          geom_bar(stat = "identity", position = position_dodge(.95))+
          geom_errorbar(aes(ymin=ymin, ymax=ymax, width=0.5), position=position_dodge(.95))+
          geom_text(position = position_dodge(width = 1), size = 6, aes(label = df.labels),
                    hjust = .5, vjust = 0, angle = 0)
    

    Plot: enter image description here