通过因子变量绘制直方图 [英] Plot histograms over factor variables
问题描述
我试图复制类似于以下(最初发现这里)
它在概念上很简单,但是我对于如何在R中完成它有点难。
总结:我想要生成24小时内行为频率的直方图一周中的每一天的一天(24级因子变量)。然后,我想将这些直方图叠加在一起,这样就可以轻松地比较一天中小时的行为分布(再次参见示例)。
例如,我的数据可能如下所示:
周日小时数
周二15 553
周一1 53
星期一10 539
星期一15 629
星期二9 281
星期六4 11
星期一3 20
星期日3 10
星期日7 2
星期天2 17
如何在上面的链接中实现图表?我对 ggplot
很糟糕,但有一个意义,这是可能的解决方案。
Thanks!
类似这样的事情?
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 $周日,水平= c(星期一,星期二,星期三,
星期四,星期五,星期六,星期天),订购= T)
df $小时< - 因子(DF $小时)
需要(GGPLOT2)$ b $碱基< - ggplot(数据= DF,AES(X =小时))$ b $碱基< - p + geom_histogram(AES(权重=计数,填补=工作日))$ b $碱基< - p + scale_fill_brewer(调色板= SET3)$ b $碱基< - p + facet_wrap(〜平日,NcoI位= 1)
p
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!
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
这篇关于通过因子变量绘制直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!