【发布时间】: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 >= 80&result<=90))) -
另一种方法。
df$mycolor<-ifelse((df$result >= 80&df$result<=90), "Group A", "Group B"); ggplot(df, aes(result,fill=mycolor))+geom_histogram(bins=, binwidth=1, )+ scale_fill_manual(values=c("darkblue", "lightblue"))