r - 使用 ggplot2 在 geom_col() 图表上方添加数据标签

标签 r ggplot2

我尝试添加显示给定 x 类别的 y 值总和的数据标签。这是我使用的代码:

library(ggplot2)
gg <- ggplot(vgsales, aes(x = Genre, y = Global_Sales, fill = Genre)) + 
geom_col() + 
geom_text(aes(x = Genre, y = Global_Sales, label = Global_Sales), stat = "sum")
print(gg)

这是我得到的结果:enter image description here

我想将标签放在每个条形上方,并仅显示给定 x 的所有 y 值的总和。我该如何实现?

编辑:我尝试使用提到的一些指南,结果是这样的:

enter image description here

因此标签似乎相互重叠并报告各个 Global_Sales 总和。有没有办法将 Global_Sales 按类型报告为标签?

最佳答案

我能够通过使用 aggregate 从我现有的数据框创建另一个数据框来找到解决方案。功能。这是结果:

library(ggplot2)
m3 <- aggregate(vgsales$Global_Sales, by=list(Genre=vgsales$Genre), FUN = sum)
m3 <- as.data.frame(m3)
names(m3) <- c("Genre", "Global_Sales")
gg <- ggplot(m3, aes(x = Genre, y = Global_Sales, fill = Genre)) + 
geom_col() +
geom_text(aes(label = Global_Sales), vjust = -0.5)
print(gg)

enter image description here

编辑:数据可以在这里找到:Video Game Sales (via Kaggle)

关于r - 使用 ggplot2 在 geom_col() 图表上方添加数据标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718365/

相关文章:

r - 向 Shiny figure 添加多个 react 性 geom_lines

r - 在包函数中访问 sysdata.rda

r - 合并具有相同名称的列表列表的元素

r - 具有交互作用的线性回归图

r - 使用插入符号创建训练和测试数据时缺少值

r - ggplot2 中 x 轴上的额外空白

r - knitr:在循环中调用 ggplot2 函数在伴随某些其他绘图函数时不会绘图

r - 使用 ggplot2 生成雷达图

r - 极柱图,最内圈为空 使用 R

r - 我可以使用 geom_rug 添加第三个变量到图形吗?