【问题标题】:R - different colors for histo-like lines in a plot based on a conditionR - 基于条件的图中类组织线的不同颜色
【发布时间】:2018-03-01 23:23:22
【问题描述】:

我有一个如下所示的 data.frame (df)

    mean      t value
    0.004      3.12
    0.021      3.41 
      .         .
      .         .
   -0.067     -3.60

我的实际 data.frame 有 90 列(90 个均值和 90 个 t 值)

现在我绘制了第一列的值(均值)

mean<-df$mean
timestamp<-seq(from=-30, to=60)
plot(mean~timestamp, type="h", lwd=2, col="darkgrey", main="test")

结果是这样的

现在我想让我的情节线根据第二列中的 t 值使用不同的颜色。

例如:如果 t 值 >2 或

我希望有办法做到这一点;) 感谢您的帮助

【问题讨论】:

    标签: r dataframe plot colors


    【解决方案1】:

    这将完成这项工作。只需要识别出符合你条件的数据,然后加上lines

    df = data.frame(mean = rnorm(91), tvalue = rnorm(91,4,1.5))
    mean<-df$mean
    timestamp<-seq(from=-30, to=60)
    t_pos = t_neg = mean
    t_pos[df$tvalue< -2 & df$tvalue >2] = NA
    t_neg[df$tvalue> -2 & df$tvalue < 2] = NA
    plot(mean~timestamp, type="h", lwd=2, col="darkgrey", main="test")
    lines(timestamp,t_pos,col="darkgrey", type = "h")
    lines(timestamp,t_neg,col="black", type ="h")
    

    【讨论】:

      【解决方案2】:

      您可以在df 中创建另一列,以指定基于tvalue 的颜色。然后您可以在plotcol 参数中指定此列。

      df$cols <- ifelse(df$tvalue < -2 | df$tvalue > 2, "black", "gray")
      with(df, plot(mean~timestamp, type="h", lwd=2, col=cols, main="test"))
      

      数据

      set.seed(510)
      df <- data.frame(mean = sample(seq(-0.1, 0.2, length.out = 91), 91), 
                       tvalue = sample(seq(-3, 3, length.out = 91), 91))
      df$timestamp <- seq(from=-30, to=60)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 2020-08-19
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        • 1970-01-01
        相关资源
        最近更新 更多