简体   繁体   English

在ggplot中结合填充和颜色图例

[英]Combine fill and color legend in ggplot

I have found some Questions similar to my issue, but none that really fit.我发现了一些与我的问题类似的问题,但没有一个真正适合。 I have 4 data columns I want to plot, 3 as lines and 1 as area.我有 4 个数据列我想要 plot,3 个作为行,1 个作为区域。

I'd like to condense the Legend of the resulting Plot into a neat 2 row, 2 column set-up, but I can't seem to figure out how.我想将生成的 Plot 的图例浓缩成一个整齐的 2 行 2 列设置,但我似乎不知道如何。 Example code:示例代码:

library(tidyverse)

#Random Data
data <- tibble(X=1:50,
               A=sample(seq(5, 6, 0.1), 50, replace = TRUE),
               B=sample(seq(4, 5, 0.1), 50, replace = TRUE),
               C=sample(seq(3, 4, 0.1), 50, replace = TRUE),
               D=sample(seq(1, 3, 0.5), 50, replace = TRUE))

ggplot(data, aes(x=X)) + 
  geom_area(aes(y=D, fill='Dataset4'), alpha=0.5) + 
  geom_line(aes(y=A, color='Dataset1')) +
  geom_line(aes(y=B, color='Dataset2')) +
  geom_line(aes(y=C, color='Dataset3')) +
  ylab("")+
  guides(fill=guide_legend(nrow=2, order=2),
         color=guide_legend(nrow=2, order=1))

Resulting figure:结果图:

在此处输入图像描述

I'd like to have the four legend entries in a 2x2 orientation, is that even possible?我想让四个图例条目以 2x2 方向排列,这可能吗?

在此处输入图像描述

You can do that by using a scale that has colour and fill aesthetics.您可以通过使用具有颜色填充美感的比例来做到这一点。 The tricky bit is letting the legend know what should be drawn as a line and what as a polygon, for which I don't have an automatic solution.棘手的一点是让图例知道什么应该画成一条线,什么应该画成一个多边形,对此我没有自动解决方案。 The manual solution below works, though you'd have to replace the 4th fill with another colour if you use a different scale.下面的手动解决方案有效,但如果您使用不同的比例,则必须用另一种颜色替换第 4 次填充。

library(ggplot2)
library(tibble)

#Random Data
data <- tibble(X=1:50,
               A=sample(seq(5, 6, 0.1), 50, replace = TRUE),
               B=sample(seq(4, 5, 0.1), 50, replace = TRUE),
               C=sample(seq(3, 4, 0.1), 50, replace = TRUE),
               D=sample(seq(1, 3, 0.5), 50, replace = TRUE))

ggplot(data, aes(x=X)) + 
  geom_area(aes(y=D, fill='Dataset4'), alpha=0.5) + 
  geom_line(aes(y=A, color='Dataset1')) +
  geom_line(aes(y=B, color='Dataset2')) +
  geom_line(aes(y=C, color='Dataset3')) +
  scale_colour_discrete(
    name = "",
    aesthetics = c("colour", "fill"),
    guide = guide_legend(
      nrow = 2, override.aes = list(
        linetype = c(1, 1, 1, 0),
        fill = c(NA, NA, NA, scales::hue_pal()(4)[4])
      )
    )
  ) +
  ylab("")
#> Warning: Duplicated override.aes is ignored.

Created on 2022-08-31 by the reprex package (v2.0.0)代表 package (v2.0.0) 于 2022 年 8 月 31 日创建

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

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