简体   繁体   English

R ggplot2堆积的条形图通过列的值进行归一化

[英]R ggplot2 stacked barplot normalized by the value of a column

I have the following dataframe t : 我有以下数据帧t

name type total
a    1    20
a    1    20
a    3    20
a    2    20
a    3    20
b    1    25
b    2    25
c    5    35
c    5    35
c    6    35
c    1    35

The total is the identical for all the entries with the same name . 对于具有相同name所有条目, total是相同的。 I want to plot a stacked barplot with type on the x axis and count of name normalized by the total on the y axis . 我想绘制一个堆积的条形图,其中x axis typecount of namey axistotal标准化。 I plotted the non normalized plot by the following : 我通过以下方式绘制了非标准化图

ggplot(t, aes(type,fill= name))+geom_bar() + geom_bar(position="fill")

How can I plot the normalized barplot ? 如何绘制标准化的条形图 ie for type = 1 the y axis value would be 2/20 for a and 1/25 for b and 1/35 for c ... 即,对于type = 1 y轴值将是2/20a1/25b1/35c ...

My try which did not work: 我的尝试不起作用:

ggplot(t, aes(type, ..count../t$total[1],fill= name))+geom_bar() + geom_bar(position="fill")

Read in the data 读入数据

d <- read.table(header = TRUE, text =
'name type total
a    1    20
a    1    20
a    3    20
a    2    20
a    3    20
b    1    25
b    2    25
c    5    35
c    5    35
c    6    35
c    1    35')

It's a bad idea to call it t , since that is the name of the transpose function. 将其称为t是一个坏主意,因为这是转置函数的名称。

Calculate the fractions 计算分数

library(dplyr)
d2 <- d %>% 
  group_by(name, type) %>% 
  summarize(frac = n() / first(total))

This is much easier to do using the dplyr package. 使用dplyr包更容易。

Make the plot 制作情节

ggplot(d2, aes(type, frac, fill = name)) +
  geom_bar(stat = 'identity')

Result 结果

在此输入图像描述

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

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