Plot histograms over factor variables

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

I'm trying to replicate the graph similar to the following (originally found HERE)

It's conceptually simple, but I'm a bit stumped as to how to do it in R.
To summarize: I want to generate histograms of behavioral frequency over the 24 hours of the day (24-level factor variable) by each day of the week. Then, I want to stack these histograms on top of each other so that the distribution of behavior over the hour of day can easily be compared (again, see example).

For example, my data might look like this:

  weekday hour    count   Tuesday   15      553    Monday    1       53    Monday   10      539    Monday   15      629   Tuesday    9      281  Saturday    4       11    Monday    3       20    Sunday    3       10    Sunday    7        2    Sunday    2       17 

How do I go about implementing the graph in the link above? I'm terrible with ggplot, but have a sense it's the likely solution. Thanks!

回答1:

Something like this?

set.seed(1234) df <- data.frame(weekday=rep(sort(unique(weekdays(.leap.seconds))), each=24),                         hour=rep(1:24, 7), count=sample(2:600, 24*7, replace=T))  df$weekday <- factor(df$weekday, levels=c("Monday", "Tuesday", "Wednesday",                        "Thursday", "Friday", "Saturday", "Sunday"), ordered=T) df$hour <- factor(df$hour)  require(ggplot2)     p <- ggplot(data = df, aes(x=hour))  p <- p + geom_histogram(aes(weights=count, fill=weekday)) p <- p + scale_fill_brewer(palette="Set3") p <- p + facet_wrap( ~ weekday, ncol=1) p 



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!