【问题标题】:Data Labels in stack bar chart using geom_col()使用 geom_col() 的堆栈条形图中的数据标签
【发布时间】:2021-03-18 15:25:18
【问题描述】:

我对 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


    【解决方案1】:

    我认为如果不手动计算百分比就无法做到这一点,但它只需要几行额外的代码。您可以按系统对数据进行分组,使用 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))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 2021-09-07
        • 1970-01-01
        相关资源
        最近更新 更多