Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

r - changing ggplot factor colors?

I notice that here Box and whiskers plot the call:

p + geom_boxplot(aes(fill = factor(cyl)))

generates bright red/green/blue colors for boxplots fill, while:

p + geom_boxplot(aes(fill = factor(vs)))

Generates a distinct pale green/red of colors. In my data, I get the second set of colors, but would like the first set (like in

p + geom_boxplot(aes(fill = factor(cyl)))

what controls which set of colors ggplot uses and how can you change it?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The default colours are evenly spaced hues around the colour wheel. You can check how this is generated from here.

You can use scale_fill_manual with those colours:

p + scale_fill_manual(values=c("#F8766D", "#00BA38"))

Here, I used ggplot_build(p)$data from cyl to get the colors.

Alternatively, you can use another palette as well like so:

p + scale_fill_brewer(palette="Set1")

And to find the colours in the palette, you can do:

require(RColorBrewer)
brewer.pal(9, "Set1")

Check the package for knowing the palettes and other options, if you're interested.

Edit: @user248237dfsf, as I already pointed out in the link at the top, this function from @Andrie shows the colors generated:

ggplotColours <- function(n=6, h=c(0, 360) +15){
  if ((diff(h)%%360) < 1) h[2] <- h[2] - 360/n
    hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
}

> ggplotColours(2)
# [1] "#F8766D" "#00BFC4"

> ggplotColours(3)
# [1] "#F8766D" "#00BA38" "#619CFF"

If you look at the two colours generated, the first one is the same, but the second colour is not the same, when n=2 and n=3. This is because it generates colours of evenly spaced hues. If you want to use the colors for cyl for vs then you'll have to set scale_fill_manual and use these colours generated with n=3 from this function.

To verify that this is indeed what's happening you could do:

p1 <- ggplot(mtcars, aes(factor(cyl), mpg)) + 
           geom_boxplot(aes(fill = factor(cyl)))

p2 <- ggplot(mtcars, aes(factor(cyl), mpg)) + 
           geom_boxplot(aes(fill = factor(vs)))

Now, if you do:

ggplot_build(p1)$data[[1]]$fill
# [1] "#F8766D" "#00BA38" "#619CFF"

ggplot_build(p2)$data[[1]]$fill
# [1] "#F8766D" "#00BFC4" "#F8766D" "#00BFC4" "#F8766D"

You see that these are the colours that are generated using ggplotColours and the reason for the difference is also obvious. I hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...