接 昨日分面报错的问题,今天突然发现我的ggplot没有按照我预先设定的颜色fill 满我的box
找debug的时候,找到别人的写的教程
https://statisticsglobe.com/r-ggplot2-warning-scale-fill-already-present
大佬就是大佬
##先画个图
data <- data.frame(group = LETTERS[1:3], # Create example data
value = 1:9)
data
ggp <- ggplot(data, aes(x = group, # Create default ggplot2 graph
y = value,
fill = group)) +
geom_boxplot()
ggp
#然后准备改颜色
#按照自己的喜好,把颜色给改了
ggp + # Applying two fill functions
scale_fill_manual(values = c("#1b98e0", "yellow", "#353436")) +
scale_fill_discrete(guide = guide_legend(reverse = TRUE))
ggp + # Applying two fill functions
+ scale_fill_manual(values = c("#1b98e0", "yellow", "#353436")) +
+ scale_fill_discrete(guide = guide_legend(reverse = TRUE))
##出现了这样的提示信息,但是我们的图呢
Scale for 'fill' is already present. Adding another scale for 'fill', which
will replace the existing scale.
>
image.png
image.png
然后我就发现,除了lenged的顺序外其余的都没变,所以原因在哪呢?
大神解释如下
The reason for this problem is that we have used multiple “fill” functions simultaneously. The ggplot2 package specifies all colors at the same time. So if we add multiple functions of the same type, ggplot2 gets confused.
也就是说它有一个 fill=group 了 后面在改颜色的时候加上
scale_fill_manual(values = c("#1b98e0", "yellow", "#353436")) +
scale_fill_discrete(guide = guide_legend(reverse = TRUE))
这样的话 这个图里面就有三个 fill了,然后ggplot2 它就迷了。它搞不懂这仨fill到底该按照哪个指示fill,所以它就不理你的后面俩fill了,直接按照默认的fill了个颜色。
修改后如下
ggp + # Applying only one fill function
scale_fill_manual(values = c("#1b98e0", "yellow", "#353436"),
guide = guide_legend(reverse = TRUE))
image.png
然后根据我自己的经历,我把我的代码也按照如上改了改。如下
##原代码
ggplot(dat1, aes(x = group, y = value,fill = type)) +
geom_boxplot(width = 0.5)+
scale_fill_manual(values=c("#78A153FF", "#DEC23BFF", "#E4930AFF",'#C53211FF'))+
scale_fill_npg()
##改后代码
ggplot(dat1, aes(x = group, y = value,fill = type)) +
geom_boxplot(width = 0.5)+
scale_fill_manual(values=c("#78A153FF", "#DEC23BFF", "#E4930AFF",'#C53211FF'),
guide = guide_legend(reverse = TRUE))+
scale_fill_npg()
我以前是没有那个guide的,天真了,我以为是这个guide 的问题,觉得它没按照我的想法搞颜色,于是就加了个guide。但是还是无济于事,继续不改色,且说着
Scale for 'fill' is already present. Adding another scale for 'fill', which will replace the existing scale.
纠结了好久,仔细品味大神的醒世金言,它迷了!
然后把我后面的 scale_fill_npg() 删了,指令就单一了,他就好了,不迷了。留下俩fill相关的指令,一个是他自己的fill = type,另一个是我给他的配色,就按照既定配色出图了。真棒!!!
ggplot(dat1, aes(x = group, y = value,fill = type)) +
geom_boxplot(width = 0.5)+
scale_fill_manual(values=c("#78A153FF", "#DEC23BFF", "#E4930AFF",'#C53211FF'),
guide = guide_legend(reverse = TRUE))
小技能加一!!
至于,配色的顺序,参照昨天的分面顺序,把需要的type顺序因子factor一下,调一下level,让因子level和颜色的顺序对应一下即可。
网友评论