gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:02:52 66 4
gpt4 key购买 nike

我尝试添加显示给定 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/

66 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com