【发布时间】:2017-06-17 06:13:43
【问题描述】:
我正在尝试使用ggplot's geom_histogram 生成一个直方图,该直方图根据渐变对条形进行着色,并对它们进行 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()
而从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()
知道为什么两个图之间的直方图条形不同并使第一个与第二个相似吗?
【问题讨论】:
-
默认情况下,
geom_histogram使用position_stack。您可以将其更改为position_identity,但您可能希望使条形透明。我建议改用分面。