ggplot在X轴下方添加跟踪颜色 [英] ggplot Adding Tracking Colors Below X-Axis

查看:47
本文介绍了ggplot在X轴下方添加跟踪颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to add a line below the x-axis where its color is dependant on a factor that is not plotted.

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

In this example, I'm creating a box plot and would like to add a line that indicates another variable.

以汽车数据集为例,然后从身体上去尝试我要做的事情:

Using the cars data set as an example and then physically dawing in what I'm trying to do:

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

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

My thought was to create a bar, column, or geom_tile plot and then arrange it below the boxplot. This is how I would do it in base R. Is there a way to add in these kinds of color labels in ggplot2?

推荐答案

ggplot2 中执行此类操作的自然方式将是在分类变量上创建子图.但是,如果您希望将所有内容都保留在同一张图上,则可以尝试使用 geom_tile()层,如下所示:

The natural way in ggplot2 to do this sort of thing would to be facet on the categorical variable to create subplots. However if you want to keep everything on the same graph you could try using a geom_tile() layer something like this:

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

Alternatively as you suggest you could align an additional plot underneath it. You could use ggarrange() in the ggpubr package for this:

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

这篇关于ggplot在X轴下方添加跟踪颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆