R中的ggplot,重新排列条形 [英] ggplot in R, reordering the bars
问题描述
我有以下情节:
score = c(5,4,8,5)
Group = c('A','A','B','B')
Time = c('1','2','1','2')
df = data.frame(score,Group,Time)
df$Group = factor(df$Group)
df$Time = factor(df$Time)
a = ggplot(df, aes(x=Time, y=score, fill=Group)) +
geom_bar(position=position_dodge(), stat="identity", width = 0.8, color = 'black')
如何重新排列这些条形,以便将A组分组在一起,然后将B组分组,并且每个条形图的x轴分别标记为时间1,2,1,2?如下图所示:
How do I reorder the bars such that Group A will be grouped together, followed by Group B, and the x-axis will be labelled as Time 1,2,1,2 for each bar? As shown below:
推荐答案
在轴上重复元素有点违反ggplot2的工作原理.但是我们可以作弊.我建议您使用@RLave使用构面的建议.但是,如果那不适合您,我会尝试不做任何尝试:
Having repeated elements on an axis is kinda against the principles of how ggplot2 works. But we can cheat a bit. I would suggest you use @RLave suggestion of using faceting. But if that doesn't suit you, I tried to do without facetting:
df2 <- rbind(df, data.frame(score=NA, Group=c('A'), Time=c('9')))
df2$x <- as.character(interaction(df2$Group, df2$Time))
ggplot(df2, aes(x=x, y=score, fill=Group)) +
geom_col(position='dodge', colour='black') +
scale_x_discrete(labels=c('1','2','','1','2')) +
theme(axis.ticks.x = element_blank(), panel.grid.major.x = element_blank())
如您所见,我们必须为x轴创建一个虚拟变量,并手动将其放置在标签上.
As you can see, we have to create a dummy variable for the x-axis, and manually put on the labels.
现在考虑使用方面更好的解决方案:
ggplot(df, aes(x=Time, y=score, fill=Group)) +
geom_col(width = 1, color = 'black') +
facet_grid(~Group) +
theme(strip.background = element_blank(), strip.text = element_blank(), panel.spacing.x=grid::unit(3, 'pt'))
面板之间的距离通过 theme
参数 panel.spacing.x
进行调整.
The distance between the panels is adjusted with the theme
argument panel.spacing.x
.
这篇关于R中的ggplot,重新排列条形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!