Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot Adding Tracking Colors Below X-Axis

Tags:

r

ggplot2

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

enter image description here

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?

like image 679
Curtis Avatar asked Sep 05 '25 13:09

Curtis


1 Answers

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

enter image description here

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

enter image description here

like image 99
G_T Avatar answered Sep 09 '25 03:09

G_T