gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:30:29 25 4
gpt4 key购买 nike

我试图找到一种方法来绘制 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")

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

谢谢,卡兰

最佳答案

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

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 值和不是直方图的预计算“高度”,那是条形图,那么我会选择其中之一。

关于r - 使用ggplot在R中具有非整数频率的多个直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34518650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com