2017-03-17 45 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