R中数据帧的直方图颜色

时间:2015-01-16 16:55:55

标签: r graphics histogram hmisc

在R中,hist.data.frame(来自Hmisc)为数据框中的每一列生成直方图,但我无法弄清楚如何更改条形的颜色。我有什么方法可以做到这一点吗?

library(Hmisc)
tmp<-data.frame(c(1,1,2,3),c(2,2,1,3))

# histograms of both columns, in white. how do I get them in blue?
hist(tmp)

1 个答案:

答案 0 :(得分:3)

Hmisc中的hist.data.frame函数没有颜色的参数选项。对hist()的所有调用都没有颜色参数。一个非常黑客的解决方法是创建自己的hist.data.frame来暂时重新定义hist()函数并允许您更改颜色。例如

hist.data.frame <- function(x, ..., colors=rainbow(ncol(x))) {
    col<-1
    hist<-function(...) {
        graphics::hist(..., col=colors[col])
        col <<- col+1
    }
    f <- Hmisc:::hist.data.frame
    environment(f) <- environment()
    f(x,...)
}

hist(iris)

enter image description here