首页 > 解决方案 > 在 R 中更改分类值的默认绘图颜色

问题描述

我刚刚编写了下面的图,我想为此修改颜色:

library(ggplot2)
library(arm)

df <- tibble::tribble(~Proportion, ~Lower,~Upper, ~Area,~Time,
                      invlogit(-0.2486022), invlogit(-0.654304025), invlogit(0.157099625), "SNP", "Day",
                      0.6878081, ( 0.6878081-0.0961473),(0.6878081+ 0.0961473), "SNP", "Night",
                      invlogit(-0.9417583), invlogit(-1.394725916), invlogit(-0.488790684),"LGCA", "Day",
                      invlogit(-0.1771685), invlogit(-0.630136116),invlogit(0.275799116), "LGCA","Night")
df


dfnew <- df %>% 
  mutate(ymin = Proportion - Lower,
         ymax = Proportion + Upper)

p <-   ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area)) +

  geom_point(size = 6, stroke = 0, shape = 16) + 
  geom_errorbar(aes(y=Proportion, ymin = Lower, ymax = Upper),width=0.1,size=1)


p<-p+theme(axis.text=element_text(size=15),
             axis.title=element_text(size=20))

p

确实,我想SNP成为颜色名称"coral"LGCA颜色名称"darkgoldenrod2"

另外,由于误差线相互重叠,我还想稍微移动点和误差线,以免重叠。

我对 R 很陌生,所以如果至少有人能指出我正确的方向,那将不胜感激!

提前致谢。

标签: rggplot2scale-color-manual

解决方案


我相信您在这里追求的是以下内容。

scale_color_manual调用中,您必须手动为每个因子级别分配一个值,如下所示:

p <-   ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area)) +
  geom_point(size = 6, stroke = 0, shape = 16) + 
  geom_errorbar(aes(y=Proportion, ymin = Lower, ymax = Upper),width=0.1,size=1) + 
  theme(axis.text=element_text(size=15),
           axis.title=element_text(size=20)) +
  scale_color_manual(values = c("SNP" = "coral", 
                                "LGCA" = "darkgoldenrod2"))
p

编辑:我错过了您问题的第二部分,误差线和点可以分别定位为不重叠使用position_dodge,如下所示:geom_pointgeom_errorbar

  geom_point(size = 6, stroke = 0, shape = 16, 
             position = position_dodge(width = 0.1)) + 
  geom_errorbar(aes(y=Proportion, ymin = Lower, ymax = Upper),width=0.1,size=1,
                position = position_dodge(width = 0.1)) + 
  theme(axis.text=element_text(size=15),
           axis.title=element_text(size=20)) +
  scale_color_manual(values = c("SNP" = "coral", 
                                "LGCA" = "darkgoldenrod2"))
p

最终情节


推荐阅读