【问题标题】:ggplot2: how to color a graph by multiple variablesggplot2:如何通过多个变量为图形着色
【发布时间】:2017-04-25 00:56:17
【问题描述】:

我相当肯定我在某处看到了解决方案,但由于我一直无法找到它,这就是我的问题。

我有一些由多个变量标识的时间序列数据,我希望能够使用 ggplot2 中的多个变量来绘制和区分颜色。

样本数据:

date <- c("2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC",
          "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC",
          "2016-06-01 UTC", "2016-04-01 UTC")
temp <- c(80.24018,  85.88911, 104.23125,  85.13571,  91.21129, 104.88333,  97.81116,
          107.40484, 121.03958,  87.91830)
id <- c("A","A","A","A","A","B","B","B","B","B")
location <- c("N","S","S","N","N","S","N","S","N","S")

df <- data.frame(date,temp,id,location)

我的绘图尝试

library(ggplot2)

ggplot(df) + 
  geom_line(aes(x=date,y=temp,colour=factor(location), group=interaction(location,id)))

使用此代码仅按位置着色。我想将线条按位置和 ID 着色。

【问题讨论】:

  • ggplot(df, aes(as.Date(date), temp, color = id, linetype = location)) + geom_path()?或ggplot(df, aes(as.Date(date), temp, color = id:location)) + geom_line(),但读起来更容易混淆。

标签: r ggplot2


【解决方案1】:

两种选择:

library(ggplot2)

df <- data.frame(date = c("2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC"),
                 temp = c(80.24018,  85.88911, 104.23125,  85.13571,  91.21129, 104.88333,  97.81116, 107.40484, 121.03958,  87.91830),
                 id = c("A","A","A","A","A","B","B","B","B","B"),
                 location = c("N","S","S","N","N","S","N","S","N","S"))

df$date <- as.Date(df$date)    # parse dates to get a nicer x-axis

id 映射到颜色,将location 映射到线型:

ggplot(df, aes(date, temp, color = id, linetype = location)) + geom_path()

...或将所有交互绘制为不同的颜色:

ggplot(df, aes(date, temp, color = id:location)) + geom_path()

【讨论】:

    【解决方案2】:

    我想提供另一种方法。我不知道为什么但是 color=id:location 对我不起作用。我通过使用tidyr::unite解决了它

    我就是这样做的:

    library(ggplot2)
    
    df <- data.frame(date = c("2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC", "2016-05-01 UTC", "2016-06-01 UTC", "2016-04-01 UTC"),
                     temp = c(80.24018,  85.88911, 104.23125,  85.13571,  91.21129, 104.88333,  97.81116, 107.40484, 121.03958,  87.91830),
                     id = c("A","A","A","A","A","B","B","B","B","B"),
                     location = c("N","S","S","N","N","S","N","S","N","S"))
    
    df$date <- as.Date(df$date) 
    
    df <- tidyr::unite(df,"id_loc",id,location,remove = F)
    ggplot(df,aes(date, temp, color = id_loc)) + geom_path()
    

    plot generated

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2013-11-20
      • 2021-11-24
      • 2017-10-03
      相关资源
      最近更新 更多