简体   繁体   English

原始 ggplot 计数条形图中的百分比

[英]Percentage in a original ggplot count barplot

I have this code:我有这段代码:

 tbl <- with(mydata, table(Species, Depth))
library(ggplot2)
ggplot(as.data.frame(tbl), aes(factor(Depth), Freq, fill = Species)) +     
  geom_col(position = 'dodge')

and this dataframe还有这个 dataframe

    Site Depth Substrate PoePres HaliPres Species
1      2   0.5      Sand       0        1  DMonte
2      2   0.5      Sand       0        1  DMonte
3      2   0.5      Sand       0        1  DMonte
4      2   0.5      Sand       0        1  DMonte
5      2   0.5      Sand       0        1  DMonte
6      2   0.5      Sand       0        1  DSandi
7      2   0.5      Sand       0        1  DSandi
8      2   0.5      Sand       0        1  DSandi
9      7   0.6      Sand       0        1  DMonte
10     7   0.6      Sand       0        1  DMonte
11     7   0.6      Sand       0        1  DMonte

That I took from this other question: Bar plot for count data by group in R我从另一个问题中得到的: Bar plot for count data by group in R

I would like to know how I could plot percentage per group ('Depth' in this case) rather than counts.我想知道每组 plot 百分比(在本例中为“深度”)而不是计数。

Thanks谢谢

We could do it this way:我们可以这样做:

library(scales)
library(ggplot2)

ggplot(df, aes(factor(Depth), fill= Species)) + 
  geom_bar(position = "dodge", aes(y = (..count..)/sum(..count..))) + 
  scale_y_continuous(labels=percent)+
  scale_fill_grey() +
  theme_bw()

在此处输入图像描述

Another option by first calculate the percentage value per group_by and use percent from scales to create percentage axis like this:另一种选择是首先计算每个group_by的百分比值并使用percent中的scales来创建百分比轴,如下所示:

library(ggplot2)
library(dplyr)
library(scales)

mydata %>% 
  count(Species, Depth) %>% 
  group_by(Depth) %>% 
  mutate(pct = n / sum(n)) %>%   
  ggplot(aes(x = factor(Depth), y = pct, fill=factor(Species))) + 
  geom_col(position="dodge") +
  scale_y_continuous(labels = percent) +
  labs(x = 'Depth', fill = 'Species')

Created on 2022-11-14 with reprex v2.0.2创建于 2022-11-14,使用reprex v2.0.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM