这使我无所适从,而且我确定我缺少一些简单的东西。任何帮助,将不胜感激。
我希望将红色和蓝色点分开,每个点都设置在对应的箱形图上,如第二幅图像所示,但具有数字x轴,如第一幅图像所示。
df <- data.frame(x = rep(c(1, 2, 10), each = 20),
g = rep(c("A", "B"), times = 30),
y = c(rnorm(60, 0, 1)))
# OK - boxplot by x and g
ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
geom_boxplot()
# Not OK. The dots are only grouped by x, not g
ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
geom_point()
# I want the points to correctly overlay the boxplots
ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
geom_boxplot(alpha = 0.1) +
geom_point()
Run Code Online (Sandbox Code Playgroud)
(我已通过在x上刻面来修复它,但我希望轴为数字以反映正确的缩放比例)
ggplot(df, aes(y = y, x = g, fill = g, color = g, group = interaction(x, g))) +
geom_boxplot(alpha = 0.1) +
geom_point() +
facet_wrap(~x)
Run Code Online (Sandbox Code Playgroud)
如果您还需要抖动,可以使用position_jitterdodge.
ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
geom_boxplot(alpha = 0.1, width=0.75) +
geom_point(position = position_jitterdodge(jitter.width=0.85))
Run Code Online (Sandbox Code Playgroud)
您可以position=position_dodge(...)在中使用geom_point。
ggplot(df, aes(y = y, x = x, fill = g, color = g, group = interaction(x, g))) +
geom_boxplot(alpha = 0.1, width=0.75) +
geom_point(position = position_dodge(width=0.75))
Run Code Online (Sandbox Code Playgroud)
我还定义了一个宽度geom_boxplot以匹配中的position_dodge宽度geom_point。
