0

I have the following plot:

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')

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:

enter image description here

TYL
  • 1,577
  • 20
  • 33
  • You can have a grid plot by adding `+ facet_grid(.~Group)`, is this what you wanted? – RLave Dec 06 '18 at 08:30
  • 2
    Do you need `ggplot(df, aes(x=Group, y=score, fill=Time)) + geom_bar(position=position_dodge(), stat="identity", width = 0.8, color = 'black') ` ? – Ronak Shah Dec 06 '18 at 08:31
  • That will group it according to Group, but the x-axis will be Group. I need the x-axis to be in Time. I have added a drawing in the main post. – TYL Dec 06 '18 at 08:50

1 Answers1

4

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())

Repeated values on x-axis

As you can see, we have to create a dummy variable for the x-axis, and manually put on the labels.

Now consider a better solution using facet:

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'))

The distance between the panels is adjusted with the theme argument panel.spacing.x.

enter image description here

MrGumble
  • 5,631
  • 1
  • 18
  • 33
  • facet_grid works better. Thanks! However, when I plot it out, the bars within a Group have white space between them (e.g., there is space between Group A Time1 and Group A Time 2). Is there anyway to remove them? – TYL Dec 06 '18 at 09:06
  • @TYL, not sure why you get white space between two columns in same panel. It might be your choice (or default) theme. Or do you still use `width=0.8` in the `geom_col`? – MrGumble Dec 06 '18 at 10:23