【问题标题】:R: Creating colorized barplot from segments()R:从段()创建彩色条形图
【发布时间】:2015-01-15 21:51:41
【问题描述】:

我正在使用segments() 函数在一个循环中绘制数百个图形。这是一些创建两个图表的简单数据。

xy <- structure(list(NAME = structure(c(2L, 2L, 1L, 1L), .Label = c("CISCO", "JOHN"), class = "factor"), ID = c(41L, 41L, 57L, 57L), X_START_YEAR = c(1965L, 1932L, 1998L, 1956L), Y_START_VALUE = c(960L, -45L, 22L, -570L), X_END_YEAR = c(1968L, 1955L, 2002L, 1970L), Y_END_VALUE = c(960L, -45L, 22L, -570L), LC = structure(c(1L, 1L, 2L, 2L), .Label = c("CA", "US"), class = "factor")), .Names = c("NAME", "ID", "X_START_YEAR","Y_START_VALUE", "X_END_YEAR", "Y_END_VALUE", "LC"), class = "data.frame", row.names = c(NA,-4L))
ind <- split(xy,xy$ID)
# Plots
for (i in ind){
  xx = unlist(i[,grep('X_',colnames(i))])
  yy = unlist(i[,grep('Y_',colnames(i))])    
  fname <- paste0(i[1, 'ID'],'.png')
  png(fname, width=1679, height=1165, res=150)
  par(mar=c(6,8,6,5))
  plot(xx,yy,type='n',main=unique(i[,1]), xlab="Time [Years]", ylab="Value [mm]",ylim = range(c(yy,-.5,.5))) 
  i <- i[,-1]
  segments(i[,2],i[,3],i[,4],i[,5],lwd=2)
  points(xx, yy, pch=21, bg='white', cex=0.8)
  abline(h=0, col = "gray60")
  dev.off()
} 

我正在尝试将其更改为带有彩色组的条形图(例如,高于 0 的每个值都是蓝色,低于 0 的值是红色)。我已经添加了我想要从其中一个结果图中实现的可视化。

据我了解barplot() 函数,我可以使用我的segments() 命令(segments(i[,2],i[,3],i[,4],i[,5])来设置每个条形图的width 选项。

我的问题: 有谁知道我可以如何更改它以便从我的数据中获取高度命令?我正在寻找 baseR 中的解决方案。

【问题讨论】:

    标签: r colors plot bar-chart segments


    【解决方案1】:

    您可以为此使用rect

    lapply(ind, function(x) {
      plot(unlist(x[, c(3, 5)]), unlist(x[, c(4, 6)]), type='n', 
           xlab='Time [Years]', ylab='Value [mm]', main=x[1, 1])
      apply(x, 1, function(y) {
        rect(y[3], min(y[4], 0), y[5], max(y[4], 0), 
             col=if(as.numeric(y[4]) < 0) 'red' else 'blue')
        abline(h=0)
      })
    })
    

    【讨论】:

    • 这看起来很棒,谢谢你的想法!我尝试将您的代码应用到我的代码中,但在转换为 as.numeric 时出现(list) object cannot be coerced to type 'double' 错误。你能看出这是什么原因吗?
    • apply 将每一行强制转换为一个向量,可以像我一样对其进行索引。如果您不在 apply 中使用它,您可能需要使用 data.frames 支持的索引,例如双括号 (y[[1]])。
    猜你喜欢
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多