用ggplot2重新创建hist()直方图

时间:2019-09-22 15:08:59

标签: r ggplot2

我正在尝试使用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:数据must be a data frame, or other object coercible by fortify(), not an S3 object with class histogram

1 个答案:

答案 0 :(得分:2)

这是一个密切的复制品:

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)

enter image description here

与您的原图非常相似: enter image description here