2017-06-16 202 views
0

我試圖產生一個直方圖ggplot' s geom_histogram根據梯度顏色的酒吧,和log10的他們。ggplot與填充和scale_y_log10結合的奇怪行爲()

下面的代碼:

library(ggplot2) 

set.seed(1) 
df <- data.frame(id=paste("ID",1:1000,sep="."),val=rnorm(1000),stringsAsFactors=F) 

bins <- 10 
cols <- c("darkblue","darkred") 
colGradient <- colorRampPalette(cols) 
cut.cols <- colGradient(bins) 
df$cut <- cut(df$val,bins) 
df$cut <- factor(df$cut,level=unique(df$cut)) 

然後,

ggplot(data=df,aes_string(x="val",y="..count..+1",fill="cut"))+ 
    geom_histogram(show.legend=FALSE)+ 
    scale_color_manual(values=cut.cols,labels=levels(df$cut))+ 
    scale_fill_manual(values=cut.cols,labels=levels(df$cut))+ 
    scale_y_log10() 

給出:enter image description here

而來自aesthetics丟棄fill

ggplot(data=df,aes_string(x="val",y="..count..+1"))+ 
    geom_histogram(show.legend=FALSE)+ 
    scale_color_manual(values=cut.cols,labels=levels(cuts))+ 
    scale_fill_manual(values=cut.cols,labels=levels(cuts))+ 
    scale_y_log10() 

給出:enter image description here

任何想法爲什麼直方圖條不同之間的兩個情節,並使第一個類似於第二個?

+0

默認情況下'geom_histogram'使用'position_stack'。您可以將其更改爲'position_identity',但您可能希望將這些條形成透明。我建議使用刻面。 – Roland

回答

2

op爲試圖以產生顏色根據梯度酒吧與ggplot的geom_histogram直方圖...

的OP已經做好了分級(10個箱),但隨後調用geom_histogram()這在默認情況下使用30個垃圾箱自己進行垃圾箱處理(請參見?geomhistogram)。

geom_bar()來代替連同的cut代替val

ggplot(data = df, aes_string(x = "cut", y = "..count..+1", fill = "cut")) + 
    geom_bar(show.legend = FALSE) + 
    scale_color_manual(values = cut.cols, labels = levels(df$cut)) + 
    scale_fill_manual(values = cut.cols, labels = levels(df$cut)) + 
    scale_y_log10() 

圖表變爲:

enter image description here

使用geom_histogram()與填充的條是如可以在this可以看出以下簡單和this answer至問題How to fill histogram with color gradient?