2017-06-16 201 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?