1

I am having trouble creating a bar chart utilizing ggplot2 that is sorted by value.

I understand that I can order the data frame by the value and then plot it. However, ggplot2 seems to ignore the ordering.

I am using the following code:

df$Frequency <- factor(dft$Frequency,  levels = df$Frequency[order(df$Frequency)])
df


# Plot the data
plot = ggplot(data=df, aes(x=Word , y=Frequency, label=Frequency)) +
  geom_bar(stat="identity") + 
  geom_text(size = 5, position = position_stack(vjust = 1.04)) +
  coord_flip()
plot

The data looks like this:

   ID Word Frequency
1  70    a       194
2  48    b       116
3 139    c       104
4 293    d        87
5  12    d        87

And I get the following plot: enter image description here

What am I missing?

Tobias
  • 35
  • 1
  • 3

1 Answers1

0

You can use reorder to order you bars. You can use the following code:

df <- data.frame(ID = c(70, 48, 139, 293, 12),
                 Word = c("a", "b", "c", "d", "e"),
                 Frequency = c(194, 116, 104, 87, 87))

plot = ggplot(data=df, aes(x=reorder(Word, -Frequency) , y=Frequency, label=Frequency)) +
  geom_bar(stat="identity") + 
  geom_text(size = 5, position = position_stack(vjust = 1.04)) +
  coord_flip() +
  labs(x = "Word")
plot

Output:

enter image description here

Use reorder(Word, Frequency):

plot = ggplot(data=df, aes(x=reorder(Word, Frequency) , y=Frequency, label=Frequency)) +
  geom_bar(stat="identity") + 
  geom_text(size = 5, position = position_stack(vjust = 1.04)) +
  coord_flip() +
  labs(x = "Word")
plot

Output:

enter image description here

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • 1
    Can also avoid coord_flip() nowadays by setting y = reorder(...), x = Frequency – jpenzer May 07 '22 at 09:18
  • Is there a way to do this without pre-calculating the frequency table? `data("diamonds"); diamonds %>% ggplot(aes(x = reorder(cut, ???)) + geom_bar()` – Fluffy Jul 24 '23 at 12:36