我有一组以多个变量为特征的记录,标记为“in”或“out”。我想绘制所有记录的汇总统计信息以及标记为“in”的那些记录,同时仅绘制每个点一次,着色以显示哪些记录为“in”或“out”。我怎样才能做到这一点?我只知道如何绘制“in”和“out”组的摘要统计信息(参见下面的代码),而不是“in”和“all”。 如果图例解释了点的颜色(如我的插图中)以及误差线的颜色,那将是一个加分。
library(data.table)
library(ggplot2)
d = data.table(v1 = rnorm(10, 0, 1),
v2 = rnorm(10, 1, 2),
g = as.factor(c(rep('in', 7), rep('out', 3))))
m = melt(d, c('g'))
print(ggplot(m, aes(x = variable, y = value, colour = g)) +
facet_wrap(~variable, scales = "free") +
geom_jitter(position = position_jitter(height = 0, width = 0.2)) +
stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.25))
答案 0 :(得分:3)
如果要显示入点和出点,但是要显示in和total的错误栏,则应移动颜色命令并为in和all添加不同的stat_summary:
library(data.table)
library(reshape2) #needed because data.table::melt will only work with reshape2
library(ggplot2)
d <- data.table(v1 = rnorm(10, 0, 1),
v2 = rnorm(10, 1, 2),
g = as.factor(c(rep('in', 7), rep('out', 3))))
m <- melt(d, c('g'))
ggplot(m, aes(x = variable, y = value)) + # removed colour here
facet_wrap(~variable, scales = "free") +
geom_jitter(aes(colour = g), position = position_jitter(height = 0, width = 0.2)) + #added color here
stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.25) + #errorbars for total observations
stat_summary(data=m[m$g == "in",], fun.data = mean_se, geom = "errorbar", width = 0.25, colour = 2) # errorbars for "in" group