我正在尝试创建一个分组的条形图,其中每个条形图上都有原始值的点图。在下面的可重现示例中,在两个时间段内进行了三种处理,因此按时间段将它们分隔开,我希望每个时间段内具有三个小节。然后,从此开始,将每个小节的原始点绘制在顶部。
现在在真实数据集中,这必须来自两个数据帧,因为每个柱的值都是独立计算的,并不代表统计摘要可以实现的简单均值或其他值。我看过其他示例和类似问题的答案,但是鉴于数据来自两个单独的数据帧,它们似乎不起作用。另外,在下面的示例中,我已经很接近了,而且距离还很短。
简单的可复制示例
df.stat <- data.frame("Y" = c(40, 30, 20, 30, 30, 30),"Time" = c(1,1,1,2,2,2), "Treatment" = c(1,2,3,1,2,3))
df.raw <- data.frame("Y.raw" = c(35,40,45,25,30,35,15,20,25,25,30,35,10,20,40,30,30,30),"Time.raw" = c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2), "Treatment.raw" = c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3))
Now if you run the code below it seems group does not produce the intended result, however, if you use fill instead of group you get the exact graph I was intending except the issue is the dots color varies per treatment instead of them all having one color across all groups.
ggplot() + geom_col(data = df.stat, aes(x = factor(df.stat$Time), y = df.stat$Y, fill = factor(df.stat$Treatment)),
color = "black", size = 1, width = .8, position = "dodge") +
geom_dotplot(data = df.raw, aes(x = factor(df.raw$Time.raw), y = df.raw$Y.raw, group = factor(df.raw$Treatment.raw)),
alpha = .8, position_dodge(width = .8), binaxis = "y",
stackdir = "center", stackratio = 1)
感谢您的任何帮助!
答案 0 :(得分:0)
这似乎可行,使用interaction
来阐明点图应同时由“处理”和“时间”来回避。 (一个提示,如果在ggplot aes()调用中使用$表示法,有时会遇到麻烦;更安全的是仅引用列名。)
ggplot() +
geom_col(data = df.stat, aes(x = factor(Time), y = Y,
fill = factor(Treatment)),
color = "black", size = 1, width = .8, position = "dodge") +
geom_dotplot(data = df.raw, aes(x = factor(Time.raw), y = Y.raw,
group = interaction(factor(Time.raw),factor(Treatment.raw))),
alpha = .8, position_dodge(width = .8), binaxis = "y",
stackdir = "center", stackratio = 1)