ggplot在X轴下添加跟踪颜色

Cur*_*tis 1 r ggplot2

我想在x轴下面添加一条线,其颜色取决于未绘制的因子.

在这个例子中,我正在创建一个箱形图,并想添加一条指示另一个变量的行.

使用汽车数据集作为示例,然后在我正在尝试做的事情中实际发现:

ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + 
geom_boxplot()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我的想法是创建一个bar,column或geom_tile图,然后将它排列在boxplot下面.这是我在基地R中的方法.有没有办法在ggplot2中添加这些颜色标签?

G_T*_*G_T 6

ggplot2做这种事情的自然方式是在分类变量上面对创建子图.但是,如果您想将所有内容保存在同一图表上,您可以尝试使用以下geom_tile()图层:

df <-data.frame(x = factor(c(4,6,8)), colour = factor(c(1,2,1)))

ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + 
  geom_boxplot()  +
  geom_tile(data=df, aes(x = x, y = 8, fill = colour)) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

或者,如您所示,您可以在其下方对齐其他绘图.您可以ggarrange()ggpubr包中使用:

plot1 <- ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + 
  geom_boxplot()  +
  geom_tile(data=df, aes(x = x, y = 10, fill = colour))
  theme(legend.position = 'none')

plot2 <- ggplot(df, aes(x=x, y=1, fill = colour)) +
  geom_tile() +
  theme_void() +
  scale_fill_manual(values=c('orange', 'green', 'orange')) +
  theme(legend.position = 'none')

library(ggpubr)

ggarrange(plot1, plot2, nrow = 2, heights = c(10, 1), align = 'h')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述