ggplot2 - 图例项目的对象

时间:2016-07-19 09:42:33

标签: r ggplot2 themes legend

我尝试绘制以下数据:

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 = '')

不幸的是,图例项目未对齐。的确,传说项目&#34; MIN / MAX范围&#34;左边比其他传奇项目更多一点&#34; MEDIAN&#34;。我试图使用命令legend.text.align但似乎没有用。

有谁知道如何对齐我的图例项目?

1 个答案:

答案 0 :(得分:2)

legend.box.just = "left"

中使用theme()

代码:

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 = '')

结果:

enter image description here