使用geom_col()在堆栈条形图中添加数据标签

问题描述 投票:0回答:3

我对 R 很陌生,我正在尝试做一个简单的堆积条形图。

这是我的数据集:

game_systems <- tibble(system = rep(c("Playstation",
                                  "Nintendo",
                                  "XBox",
                                  "NeoGeo"), 4),
                   year = c(rep(2017, 4),
                            rep(2018, 4),
                            rep(2019, 4),
                            rep(2020, 4)),
                   price = c(rep(500, 4),
                             450, 550, 250, 1000,
                             400, 600, 125, 2000,
                             350, 650, 62.5, 4000))

这是该图的代码:

game_systems %>% 
 ggplot(aes(x = system, y = price, fill = year)) + 
 geom_col(position = "fill")

这会产生以下结果:

现在我想在图中添加 % 标签作为数据标签。除了必须自己手动创建 % 值并将其放入 geom_text() 的“标签”部分之外,我似乎找不到自动执行此操作的方法

有什么想法可以做到这一点吗?

r ggplot2 data-visualization
3个回答
2
投票

我认为如果不手动计算百分比就无法完成此操作,但只需要几行额外的代码即可。您可以按系统对数据进行分组,使用 mutate() 函数计算百分比,然后将该数据输入 ggplot() 中:

game_systems %>% 
  group_by(system) %>% 
  mutate(percent = round(price/sum(price), 2)) %>% 
  ggplot(aes(x = system, y = price, fill = year)) + 
  geom_col(position = "fill") + 
  geom_text(aes(label = percent),
              position = position_fill(vjust = 0.5), 
              color = "white")

2
投票

我认为@Jacob Rothschild 的建议更直接,但如果您确实想在 ggplot 中进行计算,请添加此建议。

..y..
是 ggplot 运行时生成的一个特殊变量,可让您访问在其上下文中绘制的当前 y 值。所以
..y../sum(..y..)
相当于计算ggplot2上游的
price/sum(price)
。然后
position_fill(vjust = 0.5)
应用与
geom_col
中相同的 y“填充”,但添加了您希望标签位于每个条形中间的参数。

game_systems %>% 
  ggplot(aes(x = system, y = price, fill = year)) + 
  geom_col(position = "fill") +
  geom_text(aes(label = scales::percent(..y../sum(..y..))), 
            position = position_fill(vjust = 0.5))


0
投票

对于每个条形图,我试图获得相对百分比。为了简单起见,我更改了

x
fill
参数。代码是:

game_systems %>% 
   ggplot(aes(x = year, y = price, fill = system)) + 
   geom_col(position = "fill") +
   geom_text(aes(label = scales::percent(..y../sum(..y..))), 
        position = position_fill(vjust = 0.5))

但百分比是指数据总数。相对百分比的代码如何?我尝试了不同的解决方案,结果错误(错误的百分比)。

© www.soinside.com 2019 - 2024. All rights reserved.