Different colors for elements in boxplot

Hi:)

I am trying to add a scale of colors to a temperature boxplot graph with a red/blue scale and the hottest month’s boxplot being filled in a darker shade of red and the other one’s going down on a scale from that red to blue.

I was wondering if anyone could help?

Thanks

(I’m using ggplot)

One simple solution is to precompute the monthly average (or median, max, or min depending on how you define the "hottest month") and keep it as an additional column. That's not perfectly efficient, since you have an entire column for a few repeated values, but that shouldn't really matter in practice.

library(tidyverse)

# generate random data
expand_grid(month = as.factor(1:12),
                   day = 1:30) %>%
  add_column(temp = seq(.5,2,length.out=30*12)*rnorm(30*12, 15, 10)) %>%
  #now get the monthly statistic
  group_by(month) %>%
  mutate(monthly_temp = mean(temp)) %>%
  # and plot
  ggplot() +
  geom_boxplot(aes(x = month, y = temp, fill = monthly_temp)) +
  scale_fill_gradient2(midpoint = 20)

A more "elegant" solution could be as shown in ?geom_boxplot to use stat = "identity" and then recompute every statistic of the boxplot (ymin, lower, etc) yourself, I wouldn't recommend that approach in practice.