我知道它已经被回答了here,但仅限于ggplot2直方图。 假设我有以下代码来生成带有红色条和蓝色条的直方图,每个条的数量相同(六个红色和六个蓝色):
set.seed(69)
hist(rnorm(500), col = c(rep("red", 6), rep("blue", 7)), breaks = 10)
我想自动化整个过程,如何使用任何 x 轴的值并使用
hist()
函数设置条件为直方图条形着色(具有两种或多种颜色),而不必指定操作系统数量每种颜色的重复?
非常感谢您的帮助。
hist函数使用pretty函数来确定断点,所以你可以这样做:
set.seed(69)
x <- rnorm(500)
breaks <- pretty(x,10)
col <- ifelse(1:length(breaks) <= length(breaks)/2, "red", "blue")
hist(x, col = col, breaks = breaks)
当我想这样做时,我实际上将数据制成表格并制作如下
barplot
(请注意,表格数据的条形图是直方图):
set.seed(1337)
dat <- rnorm(500, 0, 1)
tab <- table(round(dat, 1))#Round data from rnorm because rnorm can be precise beyond most real data
bools <- (as.numeric(attr(tab, "name")) >= 0)#your condition here
cols <- c("grey", "dodgerblue4")[bools+1]#Note that FALSE + 1 = 1 and TRUE + 1 = 2
barplot(tab, border = "white", col = cols, main = "Histogram with barplot")
输出: