我使用R和ggplot来生成覆盖了各个数据点的箱图。在x轴上有两个主要的组(sampleData中的var1)。第二组也有一个次要的部门(var2),我想用点填充来表示。我已经使用ggnewscale包中的new_scale_fill函数成功地完成了这项工作。
然而,当我这样做时,它似乎改变了抖动,使得次要分割点(var2)在箱线图的左侧和右侧全部组合在一起。有没有办法避免这种情况,让所有的点在var1组中随机分组?
下面是示例数据和图形输出。
sampleData <- data.frame(numVal = c(rnorm(100)),
var1 = c(rep(c("x1", "x2"), each = 50)),
var2 = c(rep(c("x1","x2","x3"), times = c(50, 30, 20))),
var3 = c(rep(c("t1", "t2", "t3", "t4"), 25)))
ggplot(sampleData, aes(x = var1, y = numVal)) +
geom_boxplot(aes(fill = var1), alpha = 0.7) +
scale_fill_manual(values = c("red", "blue")) +
new_scale_fill() +
geom_point(aes(fill = var2), shape = 21,
position = position_jitterdodge()) +
scale_fill_manual(values = c("red", "blue", "white"))
theme(legend.position = "none")

发布于 2020-12-15 17:51:49
您可以尝试在position_jitterdodge函数中使用参数dodge.width。将dodge.width设置为零将混合蓝色和白色的点。
ggplot(sampleData, aes(x = var1, y = numVal)) +
geom_boxplot(aes(fill = var1), alpha = 0.7) +
scale_fill_manual(values = c("red", "blue")) +
new_scale_fill() +
geom_point(aes(fill = var2), shape = 21,
position = position_jitterdodge(dodge.width = 0)) +
scale_fill_manual(values = c("red", "blue", "white"))

编辑:第三个变量
如果将第三个变量放在x轴上,则可能需要控制轴和填充参数之间的交互。这是一个想法:
ggplot(sampleData, aes(x = interaction(var1,var3), y = numVal)) +
geom_boxplot(aes(fill = var1), alpha = 0.7) +
scale_fill_manual(values = c("red", "blue")) +
new_scale_fill() +
geom_point(aes(fill = interaction(var1,var2)), shape = 21,
position = position_jitterdodge(dodge.width = 0)) +
scale_fill_manual(values = c("red", "blue", "white"),
labels = c("x1", "x2", "x3"),
name = "var2") +
labs(x = "var3") +
facet_grid(.~ var3, scale = "free_x", switch = "x") +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
panel.spacing.x = unit(0, "lines"),
strip.background = element_rect(fill = "transparent"))

https://stackoverflow.com/questions/65303141
复制相似问题