ggplot2堆叠的条形图-每个条形均为100%,并且每个条形内都带有标记标签

时间:2018-07-12 12:15:47

标签: 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.

非常感谢!

3 个答案:

答案 0 :(得分:3)

ggplot(mtcars, aes(x=factor(cyl), fill = factor(am))) +
  geom_bar(position = "fill")

答案 1 :(得分:1)

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

答案 2 :(得分:1)

我知道已经晚了,但是发布它是因为我也经常寻找它...您需要:

    # Get labels
    percentData <- mtcars  %>% group_by(cyl) %>% count(am) %>%
    mutate(ratio=scales::percent(n/sum(n)))

计算每个条形图中的比例,然后绘制:

    # Plot
    ggplot(mtcars,aes(x=factor(cyl),fill=factor(am)))+
    geom_bar(position="fill")+
    geom_text(data=percentData, aes(y=n,label=ratio), 
    position=position_fill(vjust=0.5))
相关问题