gpt4 book ai didi

r - ggplot : Boxplot by several categorical variables

转载 作者:行者123 更新时间:2023-12-05 00:46:51 26 4
gpt4 key购买 nike

我正在尝试使用 ggplot2 在一张图表中绘制多个箱线图。我有 1 个连续变量和几个因素。我想要一个 Y 轴,每对箱线图都有自己的 x 轴和自己的因子水平。到目前为止,我尝试使用 cowplot::plot_grid 将我单独制作的图表与我用于 Y 轴的空图表连接在一起。我试图通过隐藏边距和调整图表大小来使图表很好地融合,但我仍然无法获得合理的结果,而且这种方法涉及太多的手动调整。
这就是我想要的,也是我目前想到的:
charts

这是我的脚本:

library(ggplot2)
library(cowplot)
library(dplyr)

# make a dataset:
DF <- mtcars
DF$cyl <- as.factor(DF$cyl)
DF$vs <- as.factor(DF$vs)
DF$am <- as.factor(DF$am)
DF$gear <- as.factor(DF$gear)
DF$carb <- as.factor(DF$carb)
#str(DF)

# fisrt boxplot
p1 <- DF %>% ggplot() + theme_grey() + aes(x=cyl, y=mpg, fill=cyl) +
geom_boxplot() +
theme(legend.position = "none",
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()) +
theme(plot.margin = margin(t=0.1, r=0, b=0, l=0, unit="cm"))

# second boxplot
p2 <- DF %>% ggplot() + theme_grey() + aes(x=vs, y=mpg, fill=vs) +
geom_boxplot() +
theme(legend.position = "none",
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank()) +
theme(plot.margin = margin(t=0.1, r=0, b=0, l=0, unit="cm"))

# empty boxplot used only for the y axis
y_axis <- DF %>% ggplot() + theme_grey() + aes(x=mpg, y=mpg) +
geom_point() +
theme(axis.title.y = element_text(),
axis.text.y = element_text(),
axis.title.x = element_text(),
axis.text.x = element_text()) +
theme(plot.margin = margin(t=0.1, r=0, b=0, l=0, unit="cm"))+
scale_x_continuous(limits = c(0, 0), breaks=c(0), labels = c(""), name="")

# join all charts toghether
p_all <- plot_grid(y_axis, p1, p2,
align="v", axis="l",
nrow=1, rel_widths = c(0.2, 1, 1))

ggdraw(p_all)

最佳答案

这是使用多个变量、一些颜色和使用 tidyr 时的样子.您可以使用 panel.border 在图之间添加边界并且应该在 facet_wrap 中指定行数为 1 :

library(ggplot2)
library(dplyr)
library(tidyr)

# Only select variables meaningful as factor
DF <- select(mtcars, mpg, cyl, vs, am, gear, carb)

DF %>%
gather(variable, value, -mpg) %>%
ggplot(aes(factor(value), mpg, fill = factor(value))) +
geom_boxplot() +
facet_wrap(~variable, scales = "free_x", nrow = 1, strip.position = "bottom") +
theme(panel.spacing = unit(0, "lines"),
panel.border = element_rect(fill = NA),
strip.background = element_blank(),
axis.title.x = element_blank(),
legend.position = "none",
strip.placement = "outside")

enter image description here

关于r - ggplot : Boxplot by several categorical variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53224089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com