ggplot() 中的堆叠和并排条形图
Stacked AND side-by-side barplot in ggplot()
我有一个包含三个因子列的数据框。一栏是'SurveyDate'栏,其他都是调查对象的属性;说一个是 'Gender' 一个是 '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)
我可以创建 table 日期频率与性别的关系,并使用它来创建并排图:
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' )
由 reprex package (v0.3.0)
于 2019-10-24 创建
更新
使用 interaction
你应该能够在填充比例上编码 2 个因子
ggplot(as.data.frame(tbl), aes(x=testDates, y=Freq, group=gender, fill = interaction(gender, graduate)))+
geom_col(位置='dodge')
我有一个包含三个因子列的数据框。一栏是'SurveyDate'栏,其他都是调查对象的属性;说一个是 'Gender' 一个是 '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)
我可以创建 table 日期频率与性别的关系,并使用它来创建并排图:
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' )
由 reprex package (v0.3.0)
于 2019-10-24 创建更新
使用 interaction
你应该能够在填充比例上编码 2 个因子
ggplot(as.data.frame(tbl), aes(x=testDates, y=Freq, group=gender, fill = interaction(gender, graduate)))+ geom_col(位置='dodge')