首页 > 解决方案 > 在 ggplot2 中创建具有不同数据集的图例

问题描述

我正在尝试在 ggplot 中创建一个图例。如果我使用同一个文件中的不同变量,我添加colour = "xx"aes 并且它可以工作。但是如果它是相同的变量但不同的数据集呢?

在下面的示例中,我从两个不同的数据集中绘制 Value ~ Year。如何创建一个用红线表示 df1 和用蓝线表示 df2 的图例?

A <- c(2001, 2002, 2003, 2004, 2005)
B <- c(3, 5, 2, 7, 5)
C <- c(2, 7, 4, 3, 5)


df1 <- data.frame(A, B)
df2 <- data.frame(A, C)

colnames(df1) <- c("Year","Value")
colnames(df2) <- c("Year","Value")


(test <- ggplot(df1, aes(Value, Year)) + geom_path(size = 1, colour='red') + 
geom_path(data=df2, colour='blue') + ylab("Year")+ scale_x_continuous(position = "top") +  scale_y_reverse(expand = c(0, 0)))

标签: rggplot2legend

解决方案


我们可以创建一个单独的数据集bind_rows并指定.id创建一个分组列,它可以aes作为“颜色”传入

library(ggplot2)
library(dplyr)
bind_rows(lst(df1, df2), .id = 'grp') %>% 
    ggplot(aes(Value, Year, colour = grp)) +
      geom_path(size = 1) + 
      ylab("Year")+ 
      scale_x_continuous(position = "top") +  
      scale_y_reverse(expand = c(0, 0))

-输出 在此处输入图像描述


推荐阅读