ggplot Adding Tracking Colors Below X-Axis

2019-07-29 20:58发布

问题:

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

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?

回答1:

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

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



标签: r ggplot2