r - 使用 ggplot2 在 R 中按值排序条形图

标签 r ggplot2

我在使用 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

我得到以下情节: enter image description here

我错过了什么?

最佳答案

您可以使用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

输出:

enter image description here

使用重新排序(单词,频率):

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

输出:

enter image description here

关于r - 使用 ggplot2 在 R 中按值排序条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72150994/

相关文章:

r - 在R控制台中覆盖当前输出

r - 从数据框列表中的每个数据框中调用特定列

html - 从 URL 渲染图像并可点击

r - 在 ggplot2 中,我可以自动将标题分成多行,而不是使用转义符\n 吗?

r - 在传单 map 上注释数字变量

r - PCA FactoMineR 绘图数据

r - 更改修改后的 ggpairs 图的轴标签(相关性热图)

r - 在 shapefile 中保存 ggplot2 coord_map() 图表

r - 如何创建ggplot列表

r - 是否有自动显示 `stargazer` 表中回归 F 统计量的 p 值的方法?