'Ordering bar chart by value in R using ggplot2 [duplicate]
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
What am I missing?
Solution 1:[1]
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:
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:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quinten |



