r - ggplot2 堆积条形图 - 每个条形图均为 100%,每个条形图内都有百分比标签

标签 r ggplot2 label bar-chart

背景: 我是 R 和 ggplot2 的新手,希望得到一个简单的答案,在相同情况下对其他人有益。

问题: 在 ggplot2 中使 每个条形添加 到 100% 并在每个条形内显示 百分比标签 的简单方法是什么?

目标: What I want it to look like(每列总计 100%,每列内带有百分比标签)。

当前图表: 这是我目前的条形图;基于“mtcars”数据集(What it currently looks like)。
下面我有“当前图表”:

library(ggplot2) # loads ggplot2
data <- mtcars # gets the mtcars dataset

#INFO: A simple barchart with X-axis being Nr of Cylinders, fill color indicating whether or not the car model has an Automatic gearbox..
# ..and Y-axis showing the count of cars by Nr of Cylinders
ggplot(mtcars, aes(x=cyl, fill = factor(am))) +
  geom_bar() +
  stat_count(geom = "text", 
             aes(label = paste(round((..count..)/sum(..count..)*100), "%")), # This row calculates the percentage across all data, adding up to 100%, but I want it to add up to 100% per X-variable (Nr of Cylinders = 4, 6, 8)
             position=position_stack(vjust=0.5), colour="white") # This row positions the bar percentage level and colors it white.

提前谢谢了!

最佳答案

library(ggplot2) # loads ggplot2
data <- mtcars 

ggplot(mtcars, aes(x=cyl, fill = factor(am))) +
  geom_bar(position = "fill") +
  stat_count(geom = "text", 
             aes(label = paste(round((..count..)/sum(..count..)*100), "%")),
             position=position_fill(vjust=0.5), colour="white")

您的代码几乎就在那里,只需要 _fill 而不是 _stack 就位。

enter image description here

关于r - ggplot2 堆积条形图 - 每个条形图均为 100%,每个条形图内都有百分比标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51305490/

相关文章:

r - 将数值向量转换为 boolean 矩阵

r - R 中复数矩阵的行列式

r - 没有ggplot2图正在工作: "Error in y[setdiff(names(y), names(x))] : object of type ' closure' is not subsettable"

r - 在 Rscript 中使用 grid.edit() 的问题

r - 匹配来自所有可能子字符串的另一个列表中的子字符串

r - 分配整数的最安全方法(担心截断)

r - 将基本图转换为 grob,保持纵横比

c# - 在标签之间切换时执行某些操作?

css - 标签不会与部分垂直对齐

string - 如何设置标签 Xamarin 表单的最大高度?