我在使用 ggplot2
创建条形图时遇到问题按值排序。
我知道我可以按值对数据框进行排序,然后绘制它。然而,ggplot2
似乎忽略了顺序。
我正在使用以下代码:
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
数据如下所示:
ID Word Frequency
1 70 a 194
2 48 b 116
3 139 c 104
4 293 d 87
5 12 d 87
我错过了什么?
最佳答案
您可以使用reorder
来对您的金条进行排序。您可以使用以下代码:
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
输出:
使用重新排序(单词,频率)
:
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
输出:
关于r - 使用 ggplot2 在 R 中按值排序条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72150994/