我已经为每个栏中的大多数类编写了一个有用的函数来着色直方图条:
color_hist <- function(x, cats, ...){
hist <- hist(x, plot=FALSE, ...)
cuts <- cut(x, breaks=hist$breaks)
color = apply(table(cuts, cats), 1, which.max)
hist(x, col=color,...)
}
color_hist(iris[,4], iris[,5])
Run Code Online (Sandbox Code Playgroud)

我想尽可能地复制行为hist(),但我无法弄清楚如何将标题和x标签从原始直方图传递到彩色化的直方图:

我希望新的直方图具有与旧直方图相同的默认标题/ xlabels,我还想通过任何其他用户指定的参数.任何人都可以帮我解决这个问题,或以其他任何方式改进这个功能?
(如果我可以让颜色相互融合,也会很酷,这取决于班级百分比......)
只需看看代码hist.default,如何在那里处理......
color_hist <- function(x, cats, xlab = xname, main = paste("Histogram of", xname), ...){
xname <- paste(deparse(substitute(x), 500), collapse = "\n")
hist <- hist(x, plot=FALSE, ...)
cuts <- cut(x, breaks=hist$breaks)
color = apply(table(cuts, cats), 1, which.max)
hist(x, col=color, xlab = xlab, main = main, ...)
}
color_hist(iris[,4], iris[,5])
Run Code Online (Sandbox Code Playgroud)
