如何使图例以默认顺序显示在数据框中

时间:2018-07-15 18:41:10

标签: r ggplot2

我正在尝试在一张图表中制作ggplot,其中包含10个以上的绘图。但是,我意识到我的专业知识无法发挥作用,因为我注意到图例的顺序与图中出现的顺序并不完全相同。还有其他方法可以添加图例而不破坏结构吗? 非常感谢。以下是供您参考的代码:

Figure1RCP45 <- ggplot(dataSet1, aes(x = Year)) +
  geom_line(aes(y = avgHist, colour = 'HISTORICAL')) +
  geom_line(aes(y = ACCESS1, colour = 'ACCESS1')) +
  geom_line(aes(y = CANESM21, colour = 'CANESM21')) +
  geom_line(aes(y = CAESM1BGC, colour = 'CAESM1BGC')) +
  geom_line(aes(y = CCSM4, colour = 'CCSM4')) +
  geom_line(aes(y = CMCC_CMS, colour = 'CMCC_CMS')) +
  geom_line(aes(y = CNRCCM5, colour = 'CNRCCM5')) +
  geom_line(aes(y = GFDL_CM3, colour = 'GFDL_CM3')) +
  geom_line(aes(y = HADGECC, colour = 'HADGECC')) +
  geom_line(aes(y = HADGEES, colour = 'HADGEES')) +
  geom_line(aes(y = MICRO5, colour = 'MICRO5')) +
  geom_line(aes(y = avgProj, colour = 'PROJECTED AVERAGE'), size = 1) +
  labs(
    title = 'First Cycle',
    x = 'Year',
    y = 'Days to mature',
    color  = 'Legend\n'
  ) +
  scale_color_manual(
    name = 'Legend',
    values = c(
      'HISTORICAL'        = 'black',
      'ACCESS1'           = 'cyan',
      'CANESM21'          = 'blue',
      'CAESM1BGC'         = 'orange',
      'CCSM4'             = 'yellow',
      'CMCC_CMS'          = 'green',
      'CNRCCM5'           = 'red',
      'GFDL_CM3'          = 'brown',
      'HADGECC'           = 'gray',
      'HADGEES'           = 'tomato',
      'MICRO5'            = 'salmon',
      'PROJECTED AVERAGE' = 'magenta'
    )
  )

Figure 2 review

1 个答案:

答案 0 :(得分:1)

1)这是在一个图形上绘制多条线(很难编写,维护和读取)的一种非常糟糕的方法,您想重塑数据。在这里Add legend to ggplot2 line plot

2)如果没有可重复的示例How to make a great R reproducible example?

,我们将无法给出具体答案

3)缩放比例的字符串值(如color一样)按字母顺序显示。如果要按特定顺序将它们转换为factor并设置级别。或者,您可以设置breaksHow to reorder the items in a legend?