如何对每个数据唯一值的绘图线进行颜色框显示?

时间:2018-08-02 17:45:33

标签: r ggplot2

我创建了一个男性和女性寿命的箱形图,每个性别的数据点都根据物种用一条线连接起来。 我的问题是,如何为每个物种分配唯一的线条颜色?由于我的数据集非常大,如果我可以自动为每个物种分配x数量的随机颜色,那将是很好的。 同样由于某种原因,我的x轴标签将不会显示出来。我希望将每个箱形图的轴标记为“性别”,然后用“雄性”和“雌性”标签。

使用此数据:

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

这段代码(取自该网站上的另一个问题-非常有用):

Longevity <- log10(News$MaleFemale.max.longevity)
# Graph plots 
r <- ggplot(News, aes(x = Sex, y = Longevity, fill = Sex)) + 
scale_x_discrete(c(labels = unique("Female","Male"), each = 2))
r <- r + geom_boxplot(color="grey40", outlier.alpha=0.0) 
r <- r + stat_summary(fun.y=mean,geom="point",pch="-",color="white",size=8,
position = position_dodge(width=0.75))
r <- r + geom_point(size=2, alpha=0.6, aes(group=Sex), data=News, position =
position_dodge(width=0.75))
r <- r + geom_line(aes(group = Binomial), alpha = 0.6, colour = "black", data
= News)  
r <- r + scale_fill_manual(values=c("#969696","#74c476"))
r <- r + theme(axis.text.x = element_text(colour = "black"), 
axis.text.y = element_text(colour = "black"),
axis.title.x = element_blank(), 
axis.title.y = element_text(colour = "black"),
legend.position = "none")
r

这是我到目前为止能够制作的:

enter image description here

1 个答案:

答案 0 :(得分:0)

之所以没有显示x标签,是因为您写了axis.title.x = element_blank()。这样可以有效地去除标签。为了获得彩色线条,应放置aes(group = Binomial, color = Binomial)并删除colour = 'black'。但是,使用这么多种颜色,您将看不到差异。无论如何,以下是带有建议编辑内容的代码的稍有清理版本。

# Graph plots 
r <- ggplot(News, aes(x = Sex, y = log10(MaleFemale.max.longevity), fill = Sex)) + 
  geom_boxplot(color="grey40", outlier.alpha=0.0) +
  stat_summary(fun.y=mean, geom="point", pch="-", color="white", size=8,
               position = position_dodge(width=0.75)) +
  geom_point(size=2, 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"), 
        axis.text.y = element_text(colour = "black"),
        axis.title.x = element_text(colour = 'black'), 
        axis.title.y = element_text(colour = "black"),
        legend.position = "none") +
  labs(y = 'Longevity')
print(r)