在ggplot2条形图中使用scales包在各个小组中而不是整个小组中累加的百分比?

问题描述

我想使用条形图(ggplot2)比较自动和手动汽车(mtcars数据集)。

我有一个在y轴上显示计数的图(下面是左侧图),但是我想要一个在y轴上带有百分比的图。

我想要这个,以便我可以更轻松地比较汽车并说,例如,“具有四个气缸的模型占自动车的x%,但仅占手动车的y%”。

我尝试使用此scales软件包教程https://www.tutorialspoint.com/how-to-create-a-bar-plot-using-ggplot2-with-percentage-on-y-axis-in-r,以一种巧妙的方式将计数转换为百分比(如下右图)。

自动和手动汽车上的百分比相加的问题。我希望将百分比分别添加自动和手动汽车中。

使用scales软件包或其他软件包可以做到这一点吗?

谢谢!

# Packages 
library(ggplot2)
library(scales)

# Data 
data(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
mtcars$am <- as.factor(mtcars$am)

# Good counts plot 
ggplot(data=mtcars,aes(x=am,fill=cyl)) +
  geom_bar(stat="count",position=position_dodge()) + scale_fill_grey() +
  ggtitle(expression(bold("mtcars")))  + xlab("automatic or manual") + ylab("count") + 
  theme(text=element_text(size=20)) + 
  theme(plot.title = element_text(size = 18,face = "bold"))

# Bad percentages plot 
ggplot(data=mtcars,fill=cyl)) +
  geom_bar(aes(y=(..count..)/sum(..count..)),position=position_dodge()) + scale_fill_grey() +
  ggtitle(expression(bold("mtcars")))  + xlab("automatic or manual") + ylab("percentage") + 
  theme(text=element_text(size=20)) + 
  theme(plot.title = element_text(size = 18,face = "bold")) 

enter image description here

解决方法

我只知道手动计算每个am的百分比(使用tidyverse):

library(tidyverse)

pl_df <- mtcars %>%
    select(am,cyl) %>%     # we're only interested in am and cyl
    group_by(am,cyl) %>%   # group data and
    add_count(cyl) %>%      # add count of cylinders (per am)
    unique() %>%            # remove dupliceas
    ungroup() %>%           # remove grouping
    group_by(am) %>%        # group by am for... 
    mutate(cyl_percentage = n/sum(n)) %>%  # ...calculating percentage
    mutate(cyl = as.factor(cyl)) %>%       # change to factors so that ggplot treats...
    mutate(am = as.factor(am))             # ...am and cyl as discrete variables

ggplot(data = pl_df,aes(x = am,fill = cyl,y = cyl_percentage)) +
    geom_bar(stat = "identity",position=position_dodge()) + 
    scale_fill_grey() +
    ggtitle(expression(bold("mtcars"))) +
    xlab("automatic or manual") + 
    ylab("percentage") + 
    theme(text=element_text(size=20)) + 
    theme(plot.title = element_text(size = 18,face = "bold")) 
,

如果您想在ggplot2内部进行全部操作(这并不总是最简单的方法),则可以执行以下操作:

ggplot(mtcars,aes(x = cyl,group = am,fill = cyl)) +
  geom_bar(aes(y = after_stat(prop),fill = factor(after_stat(x)))) + 
  scale_x_discrete(expand = c(0.5,0.2)) +
  scale_y_continuous(labels = scales::percent) +
  scale_fill_manual(values = c("gray25","gray50","gray75"),labels = levels(mtcars$cyl)) +
  facet_grid(.~am,switch = "x") +
  ggtitle(expression(bold("mtcars")))  + 
  labs(x = "automatic or manual",y = "percentage") + 
  theme(text                = element_text(size = 20),plot.title          = element_text(size = 18,face = "bold"),axis.text.x         = element_blank(),axis.ticks.length.x = unit(0,"points"),panel.spacing       = unit(0,strip.placement     = "outside",strip.background    = element_blank())

enter image description here