【问题标题】:draw several ablines at once with specific color scheme使用特定的配色方案一次绘制多个 ablines
【发布时间】:2013-12-04 16:16:05
【问题描述】:

我有一个数据框,其中斜率和截距来自一系列简单的线性回归。在绘制ablines 时,我想使用特定于类和类别的所有可能组合的颜色编码。

假设数据框如下所示:

(intercept  <-  rnorm(n = 40, mean = 1, sd = 0.25))
(slope      <-  rnorm(n = 40, mean = 2, sd = 1))
(clss       <-  c(rep("a", 20), rep("b", 20)))
(ctg        <-  c(rep("mm", 10), rep("nn", 10), rep("mm", 10), rep("nn", 10)))
df          <-  data.frame(intercept, slope, clss, ctg)

我设法使用以下方法绘制了所有 ablines:

plot(1, type="n", axes=FALSE, xlab="", ylab="", xlim=c(0, 10), ylim=c(0, 10))
mapply(abline, df$intercept, df$slope)

我想在clss=="a"ctg=="mm" 时将这些线全部绘制成绿色,并为其他clss * ctg 组合使用不同的颜色。 可能这样的事情会起作用:

by(df, paste(df$clss, df$ctg), mapply(abline, ... ))

但我不知道怎么做。

【问题讨论】:

    标签: r plot visualization


    【解决方案1】:

    使用ggplot

    library(ggplot2)
    gg       <- df
    gg$color <- paste(gg$clss,".",gg$ctg,sep="")
    ggplot(gg) +
      geom_point(aes(x=-10,y=-10,color=color)) +   # need this to display a legend...
      geom_abline(aes(slope=slope, intercept=intercept, color=color)) +
      xlim(0,10) + ylim(0,10) + labs(x="X",y="Y")
    

    产生这个:

    【讨论】:

      【解决方案2】:

      在您的情况下,您只有 4 个独特的 clssctg 组合,所以我只是选择了一些随机颜色并修改了您的 mapply

      # get colour for each combination
      x <- sample(colours(), length(unique(paste0(df$clss, df$ctg)))) 
      # how many of each combination are there
      q <-  aggregate(df$intercept, by=list(paste0(df$clss, df$ctg)), length)
      # make a colour vector
      mycols <- rep(x, q[,2])
      
      
      mapply(function(x,y,z) { abline(x, y, col=z) }, 
             df$intercept, df$slope, 
             as.list(mycols) )
      
      #You could obviously pick the colours yourself or choose a gradient
      

      【讨论】:

        猜你喜欢
        • 2020-07-10
        • 2021-02-02
        • 1970-01-01
        • 2020-07-07
        • 1970-01-01
        • 1970-01-01
        • 2017-01-30
        • 1970-01-01
        • 2019-12-22
        相关资源
        最近更新 更多