如何根据条件为ggplot中的线条着色?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何根据条件为ggplot中的线条着色?相关的知识,希望对你有一定的参考价值。

我有一个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

答案

试试这个:

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)

以上是关于如何根据条件为ggplot中的线条着色?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 ggplot 有条件地在美国地图上着色?

R:ggplot 中的因子水平被视为连续数据集

如何在片段着色器中找到 4 个顶点之间的插值位置?

ggplot2 中的误差线和线条不匹配

如何根据 ggplot2 中的某些条件删除标签?

如何根据列值更改线条的颜色