ggplot:Boxplot由几个分类变量

时间:2018-11-09 10:36:37

标签: r ggplot2 dplyr yaxis cowplot

我正在尝试使用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)

2 个答案:

答案 0 :(得分:2)

这是您想要的吗?

x <- DF
x$cars <- rownames(x)
x <- melt(x[,c("cars", "cyl", "mpg", "vs")], id.vars=c("cars", "mpg"))

ggplot(x, aes(x=value,y=mpg))+
  geom_boxplot()+
  facet_wrap(~variable, strip.position = "bottom", scales = "free_x")+
  theme(panel.spacing = unit(0, "lines"),
        strip.background = element_blank(),
        strip.placement = "outside")

我首先用melt()转换了您的数据格式,以便可以进行构面。我想您可以从这里开始,自己完成其余的格式化工作。

enter image description here

答案 1 :(得分:2)

使用多个变量,一些颜色并使用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