【问题标题】:create a legend with different datasets in ggplot2在 ggplot2 中创建具有不同数据集的图例
【发布时间】:2021-11-05 18:10:37
【问题描述】:

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

在下面的示例中,我从两个不同的数据集中绘制 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)))

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    我们可以使用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))
    

    -输出

    【讨论】:

      【解决方案2】:

      这是一个简单的解决方案,但不是一个很好的解决方案,因为你有更多的 data.frames

      library(tidyverse)
      

      代码

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

      输出

      【讨论】:

      • scale_colour_labs 会改名吗? id 喜欢将图例中的 df1 更改为不同的名称。我可以通过更改文件名来做到这一点!但是有捷径吗?
      • 是@L55,你可以设置它们,例如scale_colour_manual(values = c("df1" = "red", "df2" = "blue"),labels = c("a","b"))
      猜你喜欢
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多