【问题标题】:Recreate a hist() histogram with ggplot2使用 ggplot2 重新创建 hist() 直方图
【发布时间】:2019-09-22 15:08:59
【问题描述】:

我试图用 ggplot2 重新创建以下直方图,但没有成功。

set.seed(1234)
df <- data.frame(result=floor(rnorm(1000, 100, 20)))    
h <- hist(df$result, plot=FALSE, breaks=20)

# Selected breaks
brks <- c(80,85,90)

cols <- rep("lightblue", length(h$breaks))
# Find bars corresponding to breaks
brk_bars <- h$breaks %in% brks
cols[brk_bars] <- "darkblue"

plot(h, col=cols, main="")

我用:

library(ggplot2)
ggplot(h)+
  geom_histogram(color=cols)

但我得到Error:datamust be a data frame, or other object coercible byfortify(), not an S3 object with class histogram

【问题讨论】:

  • 我不想只是重复错误消息,但是当您需要数据框时,您已经在 h 上调用了 ggplot,这是您的 hist 对象。好像打错了
  • 是的,但我需要它像历史一样才能创建休息时间
  • 你可以用 ggplot 做到这一点。您将在geom_histogram 中设置您的 binwidth 或 bin 数量。但是文档和错误消息非常清楚,ggplot 调用中的内容必须是数据框或易于强制转换的内容
  • 这样的? ggplot(df, aes(result))+geom_histogram(bins=, binwidth = 1, aes(fill=(result &gt;= 80&amp;result&lt;=90)))
  • 另一种方法。 df$mycolor&lt;-ifelse((df$result &gt;= 80&amp;df$result&lt;=90), "Group A", "Group B"); ggplot(df, aes(result,fill=mycolor))+geom_histogram(bins=, binwidth=1, )+ scale_fill_manual(values=c("darkblue", "lightblue"))

标签: r ggplot2


【解决方案1】:

这是一个紧密的复制:

ggplot(df)+
  geom_histogram(aes(result, fill = (result<=80 | result > 95)),
                 binwidth = 5, center = 2.5, color = "black") +
  scale_fill_manual(values=c("darkblue", "lightblue"), guide = F) +
  labs(y = "Frequency", x = "Result") +
  theme_classic(base_size = 16)

与您的原版非常相似:

【讨论】:

  • 在#20处设置x轴刻度线+ scale_x_continuous(breaks=seq(40, 165, 20))
  • boundary = 0center = 2.5 的替代品。
猜你喜欢
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 2015-09-11
相关资源
最近更新 更多