使用ggplot在R中使用非整数频率的多个直方图

时间:2015-12-29 20:33:38

标签: r ggplot2

我正试图找到一种在R中绘制多个非整数频率直方图的方法。例如:

a = c(1,2,3,4,5)
a_freq = c(1.5, 2.5, 3.5, 4.5, 5.5)
b = c(2, 4, 6, 8, 10)
b_freq = c(2.5, 5, 6, 7, 8)

使用

之类的东西
qplot(x = a, weight = a_freq, geom = "histogram")

有效,但如何将b(和b_freq)叠加到此?任何想法?

如果频率是整数值,我们会这样做:

require(ggplot2) 
require(reshape2) 
set.seed(1) 
df <- data.frame(x = rnorm(n = 1000, mean = 5, sd = 2), y = rnorm(n = 1000,    mean = 2), z = rnorm(n = 1000, mean = 10)) 
ggplot(melt(df), aes(value, fill = variable)) + geom_histogram(position = "dodge")

类似的东西,当我们有非整数值时?

谢谢, 卡兰

1 个答案:

答案 0 :(得分:3)

我还不完全确定你要做什么,所以这里有四个选项:

library(ggplot2)

a = c(1,2,3,4,5)
a_freq = c(1.5, 2.5, 3.5, 4.5, 5.5)
b = c(2, 4, 6, 8, 10)
b_freq = c(2.5, 5, 6, 7, 8)

dat <- data.frame(x = c(a,b),
                                    freq = c(a_freq,b_freq),
                                    grp = rep(letters[1:2],each = 5))

ggplot(dat,aes(x = x,weight = freq,fill = grp)) + 
    geom_histogram(position = "dodge")

ggplot(dat,aes(x = x,y = freq,fill = grp)) + 
    geom_bar(position = "dodge",stat = "identity",width = 0.5)

ggplot(dat,aes(x = x,y = freq,fill = grp)) +
    facet_wrap(~grp) + 
    geom_bar(stat = "identity",width = 0.5)

ggplot() + 
    geom_bar(data = dat[dat$grp == 'a',],aes(x = x,y = freq),
                     fill = "blue",
                     alpha = 0.5,
                     stat = "identity",
                     width = 0.5) + 
    geom_bar(data = dat[dat$grp == 'b',],aes(x = x,y = freq),
                     fill = "red",
                     alpha = 0.5,
                     stat = "identity",
                     width = 0.5)

如果您有一个离散的x值和预先计算的&#34;高度&#34;这不是直方图,这是一个条形图,所以我会选择其中一个。