基于下面的示例数据集,我试图制作2个图并将它们并排放置。我已尝试使用cowplot
包来执行此操作。最后的输出非常混乱。
有没有办法可以将它们并排绘制,只显示1个图例,集中在底部(因为两个图形包含相同的元素)?
df <- data.frame(Year = c(rep(2012,5), rep(2016,5),
rep(2012,5), rep(2016,5),
rep(2012,5), rep(2016,5)),
Category = rep(c('A1','A2','A3','A4','A5'),6),
Group = rep(c('T1','T1','T1','T1','T1',
'T2','T2','T2','T2','T2',
'T3','T3','T3','T3','T3'),2),
Variable = runif(30,0,100))
plot2012 <- ggplot(df, aes(x = Group, y = Variable)) +
geom_bar(aes(fill = Category), stat = 'identity') +
ylim(0,500) +
labs(y = 'Variable') +
theme(legend.position = 'bottom',
legend.title = element_blank(),
axis.title = element_text(size = 10),
legend.text = element_text(size = 10),
axis.text = element_text(size = 10))
plot2016 <- ggplot(df, aes(x = Group, y = Variable)) +
geom_bar(aes(fill = Category), stat = 'identity') +
ylim(0,500) +
labs(y = 'Variable') +
theme(legend.position = 'bottom',
legend.title = element_blank(),
axis.title = element_text(size = 10),
legend.text = element_text(size = 10),
axis.text = element_text(size = 10))
欢迎格式/代码的任何其他一般性评论
答案 0 :(得分:3)
您可以在facet_grid
来电中添加ggplot
。
ggplot(df, aes(x = Group, y = Variable)) +
geom_bar(aes(fill = Category), stat = 'identity') +
ylim(0,500) +
labs(y = 'Variable') +
# Generate plots as panel based on Year
facet_grid(. ~ Year) +
theme(legend.position = 'bottom',
legend.title = element_blank(),
axis.title = element_text(size = 10),
legend.text = element_text(size = 10),
axis.text = element_text(size = 10))