更改R中用于分类值的默认绘图颜色

时间:2019-08-21 11:17:08

标签: r ggplot2 scale-color-manual

我刚刚编写了下面的脚本,我想为其修改颜色:

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很陌生,所以如果至少有人可以将我指向正确的方向,那将非常感激!

先谢谢了。

1 个答案:

答案 0 :(得分:2)

我相信您的追求如下。

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_dodgegeom_point中的geom_errorbar将误差线和误差点定位为不重叠: / p>

  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

Final plot