简体   繁体   English

ggplot2-添加图例

[英]ggplot2 - add legend

I have the following data: 我有以下数据:

MONTH;MEDIAN;MIN;MAX
1;-736.12;-5272.96;5946.79
2;3340.83;284.72;15707.46
3;7144.85;2916.79;17659.6
4;9927.73;1660.99;19191.29
5;10986.7;3689.15;16474.34
6;1526.48;-8086.48;13430.86
7;-4415.36;-9244.11;27554.34
8;-3213.32;-8970.76;22089.98
9;-3435.17;-5293.95;12451.59
10;-5112.405;-7002.67;5237.85
11;-7820.8;-11170.12;1164
12;-6143.055;-10836.93;165.82

I am plotting those data using the following code: 我正在使用以下代码绘制这些数据:

png("amazon_ghm.png", width = 1000, height = 400)
ggplot(amazon_ghm) +
  geom_line(aes(MONTH, MEDIAN), group=1, size = 2, color="red4") +
  geom_ribbon(aes(MONTH, ymax = MAX, ymin = MIN), alpha = 0.5, fill = "tomato1") +
  geom_hline(aes(yintercept = 0), linetype="dotted") +
  geom_text(size=9, aes(3, 25000, label = "Upper Amazon GHM"))+
  theme_bw() +
  theme(axis.text=element_text(size=20),
        axis.title=element_text(size=20),
        axis.line = element_line(colour = "black")) +
  labs(x = "Month",
      y = "Diff in runoff [m3/s]")+
  scale_x_continuous("Month", breaks = 0:12, expand = c(0,0.05))+
  scale_colour_manual(values = c("MEDIAN"="red4", "MIN/MAX range"="tomato1"))
graphics.off()

I don't know why but I can't add the legend as I want. 我不知道为什么,但是我无法根据需要添加图例。 I have tried scale_colour_manual , geom_point and a few other options but with none of them I have succeed to plot the legend. 我尝试过scale_colour_manualgeom_point和其他一些选项,但没有一个选项成功绘制了图例。

Any would be greatly appreciated! 任何将不胜感激!

You could try this: 您可以尝试以下方法:

ggplot(amazon_ghm) +
    geom_line(aes(MONTH, MEDIAN, colour = 'MEDIAN'), group=1, size = 2) +
    geom_ribbon(aes(MONTH, ymax = MAX, ymin = MIN, fill = "MIN/MAX Range"), alpha = 0.5) +
    geom_hline(aes(yintercept = 0), linetype="dotted") +
    geom_text(size=9, aes(3, 25000, label = "Upper Amazon GHM"))+
    theme_bw() +
    theme(axis.text=element_text(size=20),
          axis.title=element_text(size=20),
          axis.line = element_line(colour = "black")) +
    labs(x = "Month",
         y = "Diff in runoff [m3/s]")+
    scale_x_continuous("Month", breaks = 0:12, expand = c(0,0.05))+
    scale_colour_manual(values = c('MEDIAN' ='red4'), name = '')+
    scale_fill_manual(values = c('MIN/MAX Range' = 'tomato1'), name = '')

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM