【问题标题】:How to add percentage value in faceted barplot (qplot/ggplot/R)如何在分面条形图中添加百分比值(qplot/ggplot/R)
【发布时间】:2013-06-25 06:08:38
【问题描述】:

我有一个看起来像 this 的数据:

ENSG00000211521 MIR665 x 89
....
ENSG00000207793 MIR432 y 50
....

我想做的是制作条形图和 在每个条形图上添加“人口百分比”。 例如,值为 100 的值类别“y”, 有百分比 45.6 (132/289) 这是因为 一百个中有132个,总数 人口为 289(对于每个“x”和“y”)。

最后,我希望有一个大致如下所示的情节:

但我坚持使用以下代码。正确的做法是什么?

library(ggplot2)
dat.m <- read.delim("http://dpaste.com/1269939/plain/",sep="")
colnames(dat.m) <- c("ensg","mirna_hgc","variable","value")
qplot(value,data=dat.m, geom="bar", binwidth=1, origin=-0.05, xlim=c(50,100),ylim=c(0,75), facets=variable~.,main="")+
xlab("Value")+
ylab("Frequency")+
theme(legend.position="none")

更新:计算百分比

上图中的百分比可以通过此代码获得。 但不知何故,我找不到将它们包含到 qplot 中的方法:

dat.m <- read.delim("http://dpaste.com/1269939/plain/",sep="")
colnames(dat.m) <- c("ensg","mirna_hgc","variable","value")
# the following steps can be applied for "x"
y <- subset(dat.m,dat.m$variable=="y")
y.df <- data.frame(table(y$value))
y.df$percentage <- ((y.df$Freq)/sum(y.df$Freq) * 100)
y.df

【问题讨论】:

标签: r plot ggplot2


【解决方案1】:

你可以试试这个

qplot(value,data=dat.m, geom="bar", binwidth=1, origin=-0.05, xlim=c(50,100),ylim=c(0,75), facets=variable~.,main="")+
xlab("Value")+
ylab("Frequency")+
theme(legend.position="none") +
stat_bin(aes(label = sprintf("%.02f %%", ..count../sum(..count..)*100)),
     geom="text")

一些相关问题:

Rounding % Labels on bar chart in ggplot2

ggplot: showing % instead of counts in charts of categorical variables

【讨论】:

  • 您好,谢谢。但我无法得到正确的百分比。它给了我 10.9% 而不是 ~45%。如何修改您的代码?
  • 您可以将sum(..count..)*100 更改为28900,这是您的总人口,以确定问题是否是由于总数造成的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多