【问题标题】:How to plot time series data with different categories in ggplot 2如何在ggplot 2中绘制具有不同类别的时间序列数据
【发布时间】:2017-11-03 16:46:48
【问题描述】:

这是数据集

group <- c(1,2,3,1,2,3)
species <- c("rabbit","rabbit","rabbit","plant","plant","plant")
t1 <- c(66,77,80,4,3,1)
t2 <- c(4,5,22,1,2,6)
t100 <- c(56,78,22,1,6,7)
df <- data.frame(group, species,t1,t2,t100)

其中 ti 表示第 i 个时间帧的时间。在我的原始数据集中,我有 100 个这样的列。

我需要为数据绘制时间序列,使具有相同组号的行具有相同的颜色线,但符号不同 (pch)。理想情况下,“兔子”类别需要一个符号,“植物”类别需要另一个符号。

这是我的尝试

time <- c(1,2,100)
library(ggplot2)
ggplot(df, aes(x = time, y=df[,3:5], colour = group)) #I don't know how to take it from here

【问题讨论】:

    标签: r ggplot2 time


    【解决方案1】:

    您只需对df 进行少量修改即可实现这一目标:

    1. 通过groupspecies 融化你的df

      库(重塑) df2=melt(df, id=c("group", "species"))

    2. group 列定义为因子:

    df2$group=as.factor(df2$group)

    然后是剧情:

    ggplot(df2, aes(x=variable, y=value, colour=group, shape = species, group=interaction(group, species))) + geom_point(size=3) + geom_line(size=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 2021-03-28
      • 2020-07-18
      • 2018-11-11
      • 2012-10-30
      相关资源
      最近更新 更多