ggplot2 - 图例项目的对齐方式

ggplot2 - alignement of legend items

我尝试绘制以下数据:

amazon_ghm <- structure(
  list(MONTH = 1:12,
       MEDIAN = c(-736.12, 3340.83, 7144.85, 9927.73, 10986.7, 1526.48, -4415.36, -3213.32, -3435.17, -5112.405, -7820.8, -6143.055),
       MIN = c(-5272.96, 284.72, 2916.79, 1660.99, 3689.15, -8086.48, -9244.11, -8970.76, -5293.95, -7002.67, -11170.12, -10836.93),
       MAX = c(5946.79, 15707.46, 17659.6, 19191.29, 16474.34, 13430.86, 27554.34, 22089.98, 12451.59, 5237.85, 1164, 165.82
  )),
  .Names = c("MONTH", "MEDIAN", "MIN", "MAX"),
  row.names = c(NA, -12L),
  class = c("data.table", "data.frame"))

使用以下代码:

png("amazon_ghm.png", width = 800, height = 400)
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"),
        legend.text.align = 1,
        legend.position = c(.9, .8)) +
  labs(x = "Month",
       y = "Diff in runoff [m3/s]")+
  scale_x_continuous("Month", breaks = 0:12, expand = c(0,0.05))+
  scale_y_continuous(limits = c(-15000, 30000)) +
  scale_colour_manual(values = c('MEDIAN' ='red4'), name = '')+
  scale_fill_manual(values = c('MIN/MAX Range' = 'tomato1'), name = '')

很遗憾,图例项未对齐。实际上,图例项 "MIN/MAX range" 比另一个图例项 "MEDIAN" 更靠左。我尝试使用命令 legend.text.align 但它似乎不起作用。

有人知道如何对齐我的图例项吗?

theme()中使用legend.box.just = "left":

代码:

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"),
        legend.box.just = "left",
        legend.position = c(0.8,0.8)
        ) +
  labs(x = "Month",
       y = "Diff in runoff [m3/s]")+
  scale_x_continuous("Month", breaks = 0:12, expand = c(0,0.05))+
  scale_y_continuous(limits = c(-15000, 30000)) +
  scale_colour_manual(values = c('MEDIAN' ='red4'), name = '')+
  scale_fill_manual(values = c('MIN/MAX Range' = 'tomato1'), name = '')

结果: