繁体   English   中英

ggplot在X轴下方添加跟踪颜色

[英]ggplot Adding Tracking Colors Below X-Axis

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

在此示例中,我正在创建箱形图,并希望添加一条线来指示另一个变量。

以汽车数据集为例,然后物理上尝试做的事情:

ggplot(mtcars, aes(factor(cyl), mpg, fill=factor(am))) + 
geom_boxplot()

在此处输入图片说明

我的想法是创建一个条形图,一个柱形图或geom_tile图,然后将其布置在箱线图下方。 这是我在基准R中的处理方式。是否有办法在ggplot2中添加这些颜色标签?

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)) 

在此处输入图片说明

或者,如您建议的那样,您可以在其下方对齐另一个图。 您可以在ggpubr软件包中使用ggarrange()

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')

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM