【问题标题】:Weird behavior of ggplot combined with fill and scale_y_log10()ggplot 与 fill 和 scale_y_log10() 相结合的奇怪行为
【发布时间】: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,但您可能希望使条形透明。我建议改用分面。

标签: r ggplot2 histogram


【解决方案1】:

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()

图表变成:

thisthis answer 问题How to fill histogram with color gradient? 中可以看出,使用带有实心条的geom_histogram() 并不那么简单

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2021-12-02
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多