2017-03-17 71 views
1

我知道它已经回答here,但仅适用于ggplot2直方图。 比方说,我有以下的代码来生成与红条和蓝条,相同数量的每一个直方图(六冲和六个蓝色):具有两种或多种颜色(取决于xaxis值)的单直方图

set.seed(69) 
hist(rnorm(500), col = c(rep("red", 6), rep("blue", 7)), breaks = 10) 

我有以下的图像输出: enter image description here

我想自动化整个过程,我怎样才能使用任何x轴的值,并设置条件使用hist()函数对直方图条(使用两种或更多种颜色)进行着色,而不必指定os的重复次数每种颜色?

最受赞赏的帮助。

+0

这是真的取决于x轴值还是只是想要偶数个小节。这真的是你用种子69获得的阴谋吗?我用7个蓝色条获得了不同的情节。没有相同数量的酒吧。 – MrFlick

+0

@MrFlick不,运行这个示例代码我每次都得到相同的结果! (6蓝 - 6红)。是的,这取决于x轴的值。 – Facottons

回答

1

的HIST函数使用相当函数来确定破发点,所以你可以这样做:

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) 
+0

很好!我不知道这个'pretty()'函数。我将在我的代码中使用您的建议,并回馈我的反馈! – Facottons

2

当我想要做到这一点,我其实制表的数据,并作出barplot如下(注意,列表数据的柱状图是直方图):

set.seed(69) 
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") 

输出:

enter image description here

+0

您的解决方案非常有趣,但我真的需要'hist()'功能,所以我可以轻松地使用中断值。 – Facottons