如何使用ggplot2绘制长图例

时间:2019-10-28 17:34:02

标签: r ggplot2

我想在图表底部绘制多折线图的长图例。如何在不为图例使用较小字体的情况下做到这一点? 以下示例使用6条线,但我还使用了更多条线的图形。

library(tidyverse)
df <- tibble(d = c(1,1,2,2,3,3,4,4,5,5,6,6),
             name = c("long long long long long text 1",
                      "long long long long long text 1",
                      "long long long long long text 2",
                      "long long long long long text 2",
                      "long long long long long text 3",
                      "long long long long long text 3",
                      "long long long long long text 4",
                      "long long long long long text 4",
                      "long long long long long text 5",
                      "long long long long long text 5",
                      "long long long long long text 6",
                      "long long long long long text 6"),
             year = c(2010, 2011, 2010, 2011, 2010, 2011, 2010, 2011,
                      2010, 2011, 2010, 2011),
             value = c(0.1,0.2,0.3,0.4,0.5,0.6,0.6,0.5,0.4,0.3,0.2,0.1))

ggplot(data = df, aes(x = year, y = value)) +
  geom_line(aes(color = name, linetype = name), size = 1) +
  geom_point(aes(shape = name, color = name), size = 2) +
  theme_bw() +
  theme(axis.text.x=element_text(size=rel(1.5), angle=90),
        axis.text.y=element_text(size=rel(1.5)),
        legend.title=element_blank(),
        legend.text=element_text(size=rel(1.5)),
        legend.position = "bottom",
        axis.line = element_line(color = 'black'),
        panel.border = element_blank(),
        panel.background = element_blank(),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank()) +
  scale_x_continuous(breaks=seq(2010, 2011, by = 1)) +
  labs(
    title = "Chart title",
    x = NULL,
    y = "No."
  ) +
  ylim(0, 1)

1 个答案:

答案 0 :(得分:1)

使用guide函数控制行数或列数:

p + scale_color_discrete(guide = guide_legend(ncol = 1))

p是您上面的绘图代码。

enter image description here