我有一个包含三个因子列的数据框。一栏是“调查日期”栏,其他栏是有关调查对象的属性。说一个是“性别”,另一个是“ HighSchoolGraduate”
我想创建一个以日期为x轴并使用并排的柱状图作为男性和女性受访者人数的图,在这两个柱状图的每一个中,叠加高中毕业生与非高中毕业生。
testDates <- sample(seq(as.Date('2019/1/1'), as.Date('2019/2/1'), by="day"), 100, replace = TRUE)
gender <- sample(c("F", "M"), 100, replace = TRUE)
graduate <- sample(c("Y", "N"), 100, replace = TRUE)
testdf <- data.frame(testDates, gender, graduate)
我可以创建一个日期相对于性别的频率表,并使用它来创建并排图:
tbl <- with(testdf, table(testDates, gender))
ggplot(as.data.frame(tbl), aes(x=testDates, y=Freq, fill=gender)) +
+ geom_col(position='dodge
所以现在...我如何按毕业生划分这些酒吧? (是的,我应该为此演示创建更多示例,但是这个想法仍然有效。)
使用group
和fill
,您可以实现您描述的输出。但是,我希望从下面的输出中可以清楚地看出,这可能不是可视化数据的好方法:
library(ggplot2)
testDates <- sample(seq(as.Date('2019/1/1'), as.Date('2019/2/1'), by="day"), 100, replace = TRUE)
gender <- sample(c("F", "M"), 100, replace = TRUE)
graduate <- sample(c("Y", "N"), 100, replace = TRUE)
testdf <- data.frame(testDates, gender, graduate)
tbl <- with(testdf, table(testDates, gender, graduate))
ggplot(as.data.frame(tbl), aes(x=testDates, y=Freq, group=gender, fill = graduate)) +
geom_col(position='dodge' )
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9GNHlQdng1LnBuZyJ9” alt =“”>
由reprex package(v0.3.0)在2019-10-24创建
使用interaction
,您应该可以在填充比例尺上编码两个因子
ggplot(as.data.frame(tbl),aes(x = testDates,y = Freq,group = gender,fill =交互作用(性别,毕业生)))+geom_col(position ='dodge')
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS9jTE5COE0xLnBuZyJ9” alt =“”>