本文介绍了在ggplot2中使用闪避的条形图绘制相对频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能回答我如何绘制条形图,该条形图将数字x变量映射到由ggplot2中的一个因子分组的相对频率吗?重要的是:相对频率应计算为属于一个因素的x值内的 groupwise 频率.现在,将它们作为相对于总数个x值数量的x值进行计算.

can anybody answer how I can plot a bar-plot which maps a numeric x-variable to its relative frequency grouped by a factor in ggplot2? The important thing is:The relative frequencies should be calculated as groupwise frequencies within x-values belonging to one factor. Now they are calculated as x-values relative to the total number of x-values.

为了说明这一点,举一个例子:

To illustrates it, an example:

library(ggplot2)

data <-data.frame(x=runif(100,0:1), f=sample(1:3,100,replace=TRUE))
data$f <-factor(data$f)
p <-ggplot(data, aes(x, colour=f, fill=f, group=f)) +
    xlim(0,1) +
    scale_y_continuous('Relative Frequency', formatter='percent') # or labels=percent

让我们对它们进行多方面的绘制.然后,y轴显示比例是按组计算的.我使用了以下代码:

Let us plot them facetted. Then the y-axis shows that the proportions are calculated groupwise. I used this code:

p + stat_bin(aes(y=..count../sum(..count..)), position='dodge', binwidth=0.2) +         facet_grid(~f)

让我们密谋规避他们. y轴显示比例指的是整个数据集.在这里,我使用了以下代码:

Let us plot them dodged. The y-axis shows that the proportions refer to the whole dataset. Here, I used the following code:

p + stat_bin(aes(y=..count../sum(..count..)), position='dodge', binwidth=0.2)

我的目标是创建一个类似于第二个图的图,并在y轴上显示每组变量的频率.

I aim at creating a plot like the second with the frequencies of the variable per group on the y-axis.

非常感谢您的提前帮助!贾娜

Thank a lot for your help in advance!Jana

推荐答案

我遇到了与您相同的问题,并且发现了问题:绘制..density..*your_binwidth而不是绘制..count../sum(..count..)实际上,bin stat创建的..density..变量基本上等于比例/绑定宽度.您的代码将变为:

I was facing the same problem as yours and I figured it out: instead of plotting ..count../sum(..count..), plot ..density..*your_binwidthIndeed, the ..density.. variable created by the bin stat is basically equal to proportion/bindwidth.Your code becomes:

p + stat_bin(aes(y=..density..*0.2), position='dodge', binwidth=0.2)

这篇关于在ggplot2中使用闪避的条形图绘制相对频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:05