更改 ggplot 因子颜色 [英] Change 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)))
什么控制 ggplot 使用的颜色集以及如何更改它?
What controls which set of colors ggplot uses and how can you change it?
推荐答案
默认颜色是围绕色轮均匀分布的色调.您可以从此处查看这是如何生成的.
The default colours are evenly spaced hues around the colour wheel. You can check how this is generated from here.
您可以将 scale_fill_manual
用于这些颜色:
You can use scale_fill_manual
with those colours:
p + scale_fill_manual(values=c("#F8766D", "#00BA38"))
在这里,我使用了 cyl
中的 ggplot_build(p)$data
来获取颜色.
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.
@user248237dfsf,正如我已经在顶部链接中指出的那样,@Andrie 的这个函数显示了生成的颜色:
@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"
如果看生成的两种颜色,第一种颜色是一样的,但是第二种颜色就不一样了,当n=2和n=3的时候.这是因为它生成均匀间隔色调的颜色.如果您想将 cyl
的颜色用于 vs
,那么您必须设置 scale_fill_manual
并使用从 n=3 生成的这些颜色这个功能.
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)))
现在,如果你这样做:
ggplot_build(p1)$data[[1]]$fill
# [1] "#F8766D" "#00BA38" "#619CFF"
ggplot_build(p2)$data[[1]]$fill
# [1] "#F8766D" "#00BFC4" "#F8766D" "#00BFC4" "#F8766D"
您看到这些是使用 ggplotColours
生成的颜色,差异的原因也很明显.我希望这会有所帮助.
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.
这篇关于更改 ggplot 因子颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!