How do I change the outline colours of a boxplot with ggplot?

我的未来我决定 提交于 2019-12-11 04:45:04

问题


My data has values which are all the same so they are coming up as just a line in a box plot. This, however, means that I can't tell the difference between groups as the fill doesn't show up. How can I change the outlines of the boxplot to be a specific colour.

Note: I do not want all the outline colours to be the same colour, as in the next line of code:

library(dplyr)
library(ggplot2)

diamonds %>% 
      filter(clarity %in% c("I1","SI2")) %>% 
    ggplot(aes(x= color, y= price, fill = clarity))+
      geom_boxplot(colour = "blue")+
      scale_fill_manual(name= "Clarity", values = c("grey40", "lightskyblue"))+
      facet_wrap(~cut)

Instead, I would like all the plots for I1 (filled with grey40) to be outlined in black while the plots for SI2 (filled with lightskyblue) to be outlined in blue.

The following don't seem to work

geom_boxplot(colour = c("black","blue"))+

OR

scale_color_identity(c("black", "blue"))+

OR

scale_color_manual(values = c("black", "blue"))+

回答1:


You have to:

  1. Add color = clarity to aesthetics
  2. Add scale_color_manual to ggplot object with wanted colors
  3. Name scale_color_manual the same way as scale_fill_manual to get single combined legend

Code :

library(dplyr)
library(ggplot2)
diamonds %>% 
    filter(clarity %in% c("I1","SI2")) %>% 
    ggplot(aes(x= color, y= price, fill = clarity, color = clarity))+
        geom_boxplot()+
        scale_fill_manual(name= "Clarity", values = c("grey40", "lightskyblue"))+
        scale_color_manual(name = "Clarity", values = c("black", "blue"))+
        facet_wrap( ~ cut)

Plot:



来源:https://stackoverflow.com/questions/46907040/how-do-i-change-the-outline-colours-of-a-boxplot-with-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!