Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用geom_col()的堆栈条形图中的数据标签_R_Ggplot2_Data Visualization - Fatal编程技术网

R 使用geom_col()的堆栈条形图中的数据标签

R 使用geom_col()的堆栈条形图中的数据标签,r,ggplot2,data-visualization,R,Ggplot2,Data Visualization,我对R很陌生,我正在尝试做一个简单的堆叠条形图 这是我的数据集: game_systems <- tibble(system = rep(c("Playstation", "Nintendo", "XBox", "Neo

我对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))
这将产生以下结果:

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


你知道如何做到这一点吗?

我认为不需要手动计算百分比就可以做到这一点,但只需要几行额外的代码。您可以按系统对数据进行分组,使用mutate()函数计算百分比,然后将数据输入ggplot():


我认为这不需要手动计算百分比,但只需要几行额外的代码。您可以按系统对数据进行分组,使用mutate()函数计算百分比,然后将数据输入ggplot():


我认为@Jacob Rothschild的建议更直截了当,但如果您确实想在ggplot中进行计算,请添加此选项
.y..
是运行ggplot时生成的一个特殊变量,用于访问在其上下文中绘制的当前y值。因此
.y../sum(..y..)
相当于计算ggplot2上游的
价格/sum(价格)
。然后
position\u fill(vjust=0.5)
应用与
geom\u col
中相同的y“fill”,但添加了一个参数,希望标签位于每个条的中间

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))

我认为@Jacob Rothschild的建议更直截了当,但如果您确实想在ggplot中进行计算,请添加此选项
.y..
是运行ggplot时生成的一个特殊变量,用于访问在其上下文中绘制的当前y值。因此
.y../sum(..y..)
相当于计算ggplot2上游的
价格/sum(价格)
。然后
position\u fill(vjust=0.5)
应用与
geom\u col
中相同的y“fill”,但添加了一个参数,希望标签位于每个条的中间

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))

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))