如何根据条件对ggplot中的线进行着色?

时间:2018-08-03 14:32:34

标签: r ggplot2

我有一个ggplot,用线条显示了许多物种的雄性和雌性寿命之间的关系。由于不清楚有多少条直线穿过,所以我想在情节上放置一个条件,以便如果某物种的雄性长寿>雌性长寿,则该线将为黑色,如果不是,则该线将为红色(即男性寿命<或=女性寿命)。

我正在使用这些数据

`MaleFemale.max.longevity    Sex Binomial
195 Male    Agouti_paca
192 Female  Agouti_paca
196 Male    Alopex_lagopus
126 Female  Alopex_lagopus
240 Male    Amblonyx_cinereus
276 Female  Amblonyx_cinereus
254 Male    Aotus_azarai
174 Female  Aotus_azarai
310 Male    Arctictis_binturong
324 Female  Arctictis_binturong
430 Male    Cacajao_calvus
276 Female  Cacajao_calvus
314 Male    Callicebus_moloch
244 Female  Callicebus_moloch
223 Male    Callithrix_pygmaea
181 Female  Callithrix_pygmaea
164 Male    Canis_adustus
130 Female  Canis_adustus`

当前正在使用此代码(根据物种为线着色)

`r <- ggplot(News, aes(x = Sex, y = log10(MaleFemale.max.longevity), fill = 
Sex)) +
stat_summary(fun.y=mean, geom="point", pch="-", color="white", size=8,
position = position_dodge(width=0.75)) +
geom_point(size=5, alpha=0.6, aes(group=Sex),
position = position_dodge(width=0.75)) +
geom_line(aes(colour = Binomial, group = Binomial), alpha = 0.6)  +
scale_fill_manual(values=c("#969696","#74c476")) +
theme(axis.text.x = element_text(colour = "black", size=30), 
axis.text.y = element_text(colour = "black",size=30),
axis.title.x = element_text(colour = "black",size=30), 
axis.title.y = element_text(colour = "black",size=30),
legend.position = "none") +
labs(y = 'Longevity', title="Polygynous system")
print(r)`

非常感谢您的帮助-Nik

1 个答案:

答案 0 :(得分:0)

尝试一下:

library(dplyr)
News <- spread(News, key="Sex", value=MaleFemale.max.longevity) %>%
  mutate(malelonger = Male > Female) %>%
  gather(key="Sex", value= "MaleFemale.max.longevity", c("Male", "Female"))


r=ggplot(News, aes(x = Sex, y = log10(MaleFemale.max.longevity), fill = 
                        Sex)) +
  stat_summary(fun.y=mean, geom="point", pch="-", color="white", size=8,
               position = position_dodge(width=0.75)) +
  geom_point(size=5, alpha=0.6, aes(group=Sex),
             position = position_dodge(width=0.75)) +
  geom_line(aes(colour = malelonger, group = Binomial), alpha = 0.6)  +
  scale_fill_manual(values=c("#969696","#74c476")) +
  theme(axis.text.x = element_text(colour = "black", size=30), 
        axis.text.y = element_text(colour = "black",size=30),
        axis.title.x = element_text(colour = "black",size=30), 
        axis.title.y = element_text(colour = "black",size=30),
        legend.position = "none") +
  labs(y = 'Longevity', title="Polygynous system")+
  scale_colour_manual(values=c("red2", "black"))
print(r)