Fill boxplot color based on value gradient

2019-07-27 18:50发布

问题:

I want to color the boxplot based the value on y axis using a color gradient. I added the legend filled with red to blue gradient but I don't know how to add those colors into each box.

library(ggplot2)

ggplot(mpg, aes(class, hwy))+ geom_boxplot(aes(colour = hwy))+
 scale_fill_gradient2(low = "red", high = "blue", 
   midpoint = 25, limit = c(0,50), space = "Lab", 
   name="hwy")

回答1:

I don't think you can. ggplot documentation only mentions coloring by a factor, and I see only factor that has been specified on x axis.

Also when you think about it your statement is ambigious, what in the box plot determines fill? Median, Upper Boundary, Lower Boundary?

Update:

This isn't exactly what you asked for but its close.

mpg %>% 
  group_by(class) %>% 
  mutate(mean.hwy= mean(hwy)) %>% 
  ggplot( aes(class, hwy)) +
    geom_boxplot() +
    stat_summary(fun.y= "mean",
                 aes(y=mean.hwy,color=mean.hwy),
                 geom = "point") +
    scale_color_gradient2(low = "red", 
                          high = "blue", 
                          midpoint = 25, 
                          limit = c(0,50), 
                          space = "Lab", 
                          name="hwy")

For some reason I couldn't get this to work with median which I guess would make more sense here but hopefully this will get you closer to your goal.



标签: r plot ggplot2