R ggplot2堆叠条形图,y轴上的百分比,以条为单位 [英] R ggplot2 stacked barplot, percent on y axis, counts in bars

查看:65
本文介绍了R ggplot2堆叠条形图,y轴上的百分比,以条为单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在格式化ggplot2时遇到问题,无法显示堆叠的条形图,其Y轴上的累积百分比和条形图内的计数.我可以对每种类型绘制一个图(一个在Y轴上带有百分比的图,一个在条形图中带有计数的图),但不能同时绘制两个图.这就是我所拥有的:

I'm having a problem formatting ggplot2 to display a stacked bar plot with cumulative percent on the Y axis and counts within the bars. I can do one plot of each type (one with percent on the Y axis, one with counts in the bars) but not both. Here's what I have:

group <- c(1,1,1,2,2,2)
ind <- c(1,2,3,1,2,3)
count <- c(98,55,10,147,31,3)
df <- data.frame(group, ind, count)

library(ggplot2)
library(scales)

ggplot(df, aes(y=count, x=factor(group), fill=factor(ind), label=cfreq)) +
geom_bar(stat = "identity") + ylab("Percent Level 1 Classes") +
scale_fill_discrete(name="Level 1\nClasses") +
xlab("Level 2 Groups") +
geom_text(size = 3, position = position_stack(vjust = 0.5))

这将产生以下带有计数但在Y轴上没有百分比的图:

This produces the following plot with counts but no percent on Y axis:

该图的第二个版本在Y轴上生成百分比,但在条形图中没有计数:

The second version of the plot produces the percent on the Y axis but no counts in the bars:

ggplot(df, aes(y=count, x=factor(group), fill=factor(ind))) +
geom_bar(position = "fill", stat = "identity") + 
ylab("Percent Level 1 Classes") +
scale_fill_discrete(name="Level 1\nClasses") +
xlab("Level 2 Groups")

但是我不能同时做到这两个.我没有浪费空间,而是在"aes"语句中尝试了"label = cfreq",但无济于事-似乎与"geom_text"选项冲突.任何帮助将不胜感激.

But I can't get it to do both. Rather than waste space, I did try "label=cfreq" in the "aes" statement to no avail--seems to conflict with the "geom_text" option. Any help would be greatly appreciated.

推荐答案

这似乎可以满足您的要求:

This seems to do what you want:

group <- c(1,1,1,2,2,2)
ind <- c(1,2,3,1,2,3)
count <- c(98,55,10,147,31,3)
df <- data.frame(group, ind, count)

library(ggplot2)
library(scales)

ggplot(df, aes(y=count, x=factor(group), fill=factor(ind))) +
  geom_bar(position = "fill", stat = "identity") +
  geom_text(aes(label = count), position = position_fill(vjust = 0.5)) +
  ylab("Percent Level 1 Classes") +
  scale_fill_discrete(name="Level 1\nClasses") +
  xlab("Level 2 Groups")

我认为默认情况下该位置设置为身份",而堆栈"设置为也不是解决问题的原因,因为标签似乎是在计数的原始比例上,而不是在百分比上,因此条形图基本上缩小到了图底部的一条线.使用 vjust = 0.5 将标签居中,因为默认值为1,这会将它们放在条形图的顶部.

I think by default the position is set to "identity", and "stack" doesn't solve the problem either because the labels seem to be on the original scale of the counts, not the percents, so the bars get shrunk down to basically a line at the bottom of the plot. Using vjust = 0.5 centers the labels, since the default is 1, which puts them at the top of the bars.

这篇关于R ggplot2堆叠条形图,y轴上的百分比,以条为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆