【问题标题】:How to specify the color of bars in a table plot in R如何在R中的表格图中指定条形的颜色
【发布时间】:2020-02-18 21:54:48
【问题描述】:

假设我有数据D。我把cut这个数据分成了3个。如何为 R 图中的每条数据分配不同的颜色?

注意:我对任意数量的数据切割的功能性答案感兴趣。

这是我的数据和 R 代码(没有成功):

# DATA
D <- read.csv("https://raw.githubusercontent.com/rnorouzian/m/master/t.csv", h = TRUE)

# cut in 3 pieces
g <- table(cut(D$time, 
               breaks = c(-Inf, 4, 12, Inf), 
               include.lowest=TRUE))

# color DATA based on pieces: [0-4], [6-12], [24-40]
plot(table(D$time), col = (1:3)[g])  

【问题讨论】:

    标签: r function dataframe plot


    【解决方案1】:

    在基础 R 绘图中为点着色的技巧是指定一个“短”颜色向量(例如,col_vec &lt;- c("red", "blue")),然后为您的点/线指定通常“长”的类别向量(例如,@ 987654324@。然后在对plot()的调用中使用参数col = col_vec[cat_vec]

    这对于您绘制表格对象的愿望基本上会做同样的事情:

    # identify the categories of each row of data
    D$cat <- cut(D$time, breaks = c(-Inf, 4, 12, Inf))
    
    # get a vector of the colors -- one color per group
    color_vec <- colorRampPalette(c(4,2))(length(unique(D$cat)))
    
    # get a vector of the color per value of D$time
    category_vec <- aggregate(cat ~ time, data=D, function(i) mean(as.integer(i)))[,2]
    
    # plot it as described in paragraph above
    plot(table(D$time), col=color_vec[category_vec])
    

    【讨论】:

      【解决方案2】:
      # DATA
      D <- read.csv("https://raw.githubusercontent.com/rnorouzian/m/master/t.csv", h = TRUE)
      
      # cut in 3 pieces    
      g <- cut(as.numeric(names(table(D$time))), 
                     breaks = c(-Inf, 4, 12, Inf), 
                     include.lowest=TRUE)
      
      # color DATA based on pieces: [0-4], [6-12], [24-40]
      plot(table(D$time), col = g)  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        • 2020-04-11
        • 2022-12-10
        • 2021-02-25
        • 2013-02-11
        • 2018-08-22
        • 2014-02-11
        相关资源
        最近更新 更多