R中带有附加点的箱形图
box plot in R with additional point
我有一个包含不同范围的多列数据框(假设为 n
)和一个长度为 n
的向量。我希望每个变量的不同 x 轴显示在每个箱线图下方。我试过 facet_grid
和 facet_wrap
但它给出了共同的 x 轴。
这是我试过的:
d <- data.frame(matrix(rnorm(10000), ncol = 20))
point_var <- rnorm(20)
plot.data <- gather(d, variable, value)
plot.data$test_data <- rep(point_var, each = nrow(d))
ggplot(plot.data, aes(x=variable, y=value)) +
geom_boxplot() +
geom_point(aes(x=factor(variable), y = test_data), color = "red") +
coord_flip() +
xlab("Variables") +
theme(legend.position="none")
如果您可以接受 x 轴文本位于图上方,并且图表的顺序有点混乱,这可能会起作用:
library(grid)
p = ggplot(plot.data, aes(x = 0, y=value)) +
geom_boxplot() +
geom_point(aes(x = 0, y = test_data), color = "red") +
facet_wrap(~variable, scales = "free_y", switch = "y") +
xlab("Variables") +
theme(legend.position="none") + theme_bw() + theme(axis.text.x=element_blank())
print(p, vp=viewport(angle=270, width = unit(.75, "npc"), height = unit(.75, "npc")))
实际上我只是在不翻转坐标的情况下创建图形,因此 scales = 'free_y'
可以工作,切换条带标签的位置,然后旋转图形。
如果您不喜欢图表上方的文字(这是可以理解的),我会考虑创建一个单图列表,然后将它们与 grid.arrange
.
放在一起
HTH,
洛伦佐
我有一个包含不同范围的多列数据框(假设为 n
)和一个长度为 n
的向量。我希望每个变量的不同 x 轴显示在每个箱线图下方。我试过 facet_grid
和 facet_wrap
但它给出了共同的 x 轴。
这是我试过的:
d <- data.frame(matrix(rnorm(10000), ncol = 20))
point_var <- rnorm(20)
plot.data <- gather(d, variable, value)
plot.data$test_data <- rep(point_var, each = nrow(d))
ggplot(plot.data, aes(x=variable, y=value)) +
geom_boxplot() +
geom_point(aes(x=factor(variable), y = test_data), color = "red") +
coord_flip() +
xlab("Variables") +
theme(legend.position="none")
如果您可以接受 x 轴文本位于图上方,并且图表的顺序有点混乱,这可能会起作用:
library(grid)
p = ggplot(plot.data, aes(x = 0, y=value)) +
geom_boxplot() +
geom_point(aes(x = 0, y = test_data), color = "red") +
facet_wrap(~variable, scales = "free_y", switch = "y") +
xlab("Variables") +
theme(legend.position="none") + theme_bw() + theme(axis.text.x=element_blank())
print(p, vp=viewport(angle=270, width = unit(.75, "npc"), height = unit(.75, "npc")))
实际上我只是在不翻转坐标的情况下创建图形,因此 scales = 'free_y'
可以工作,切换条带标签的位置,然后旋转图形。
如果您不喜欢图表上方的文字(这是可以理解的),我会考虑创建一个单图列表,然后将它们与 grid.arrange
.
HTH,
洛伦佐