使用分组变量ggplot2在折线图中创建图例

时间:2017-06-07 18:44:22

标签: r ggplot2 legend

我的数据看起来像这样,其中line是表示遗传线的分组变量,tp是时间点(x轴),expr是相对于0尖点的基因表达,并且col是每行的颜色分配:

line    tp    expr           col
358 LL  0   0                yellowgreen
358 LL  30  -2.459476064     yellowgreen
358 LL  60  0.645900697      yellowgreen
358 LL  90  0.040513329      yellowgreen
380 LL  0   0                indianred4
380 LL  30  0.893111431      indianred4
380 LL  60  0.847461181      indianred4
380 LL  90  -0.867875889     indianred4
441 HL  0   0                blue
441 HL  30  1.934555631      blue
441 HL  60  3.144618461      blue
441 HL  90  1.883829994      blue
486 LL  0   0                bisque4
487 LL  30  -0.064427095     bisque4
488 LL  60  0.015498302      bisque4
489 LL  90  1.047567166      bisque4
832 HL  0   0                blueviolet
832 HL  30  -0.233381601     blueviolet
832 HL  60  -3.562884526     blueviolet
832 HL  90  -0.038818998     blueviolet
913 HL  0   0                orange
913 HL  30  0.799850689      orange
913 HL  60  0.818883617      orange
913 HL  90  -0.07758268      orange
Average 0   0                black
Average 30  0.145038832      black
Average 60  0.318246289      black
Average 90  0.331272154      black

使用以下代码,我完全按照我想要的方式制作,但没有传说:

# Set color spectrums:
larvae_col <- as.vector(CG13288_L$col)

ggplot(data=CG13288_L, aes(x = tp, y = expr, group=line)) + 
  geom_line(size=1, color=larvae_col) + 
  theme_light() + theme(panel.grid=element_blank()) +
  labs(title="CG13288 (FBgn0035648) - Larvae", x="Time Point", y="LogFC Expression") +
  theme(axis.title.x = element_text(color="black", face="bold", size=35, margin=margin(20,0,0,0))) +
  theme(axis.title.y = element_text(color="black", face="bold", size=35, margin=margin(0,20,0,0))) +
  theme(plot.title=element_text(color="black", face="bold", size=40, margin=margin(0,0,20,0))) +
  theme(axis.text = element_text(size=30, color="black", face="bold")) +
  theme(panel.border = element_rect(color = "black", size=1.5)) +
  theme(axis.ticks = element_line(color = "black", size=1.5)) +
  scale_x_discrete(expand=c(0.01,0.04)) +
  scale_y_continuous(limits=c(-4,4), breaks=c(-4,-2,0,2,4), expand=c(0.02,0.01))

ggsave("CG13288_L.pdf", plot = last_plot(), device = "pdf", width = 15, height = 10, units = "in", useDingbats=FALSE)

我玩弄了第一行使用“color”而不是“group”,但每个tp(时间点)都有垂直线。如何为此添加图例?

1 个答案:

答案 0 :(得分:0)

如果希望变量自动出现在图例中,则应在aes对象中指定它。 只需将第2行更改为:

geom_line(size=1, aes(colour=col)) +

这样您的图例就会将颜色名称指定为ggplot默认颜色。要更改默认的ggplot颜色,您可以添加:

scale_colour_manual(values=unique(larvae_col))