1

I'd like the x-axis of my barchart to be a continuous scale.

Here is my data:

list(
 Century = c(1, 2, 3, 4, 5), 
 CenturyLabel = c("1st", "Bit later", "", "", "Post-Roman"), 
 Value = c(.2, .3, 0, 0, .4) ) %>% as_tibble()

I'm hoping to see bars for the 1st, 2nd, and 5th centuries with gaps for the 3rd and 4th.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
James Bejon
  • 189
  • 5
  • `df %>% ggplot(aes(x = Century, y = Value)) + geom_col()` ? – JasonAizkalns Jun 10 '19 at 16:01
  • In general you do something like this: https://stackoverflow.com/questions/12040245/how-to-increase-the-space-between-the-bars-in-a-bar-plot-in-ggplot2 but ggplot doens't make it easy to specify different gaps between different bars (since that makes the axis meaningless). Might need to do some post-processing in another program for that. – MrFlick Jun 10 '19 at 16:05
  • Another option: https://stackoverflow.com/questions/30100500/specific-spaces-between-bars-in-a-barplot-ggplot2-r – MrFlick Jun 10 '19 at 16:06

1 Answers1

1

The trick is to define your x-axis variable as a factor.

library("dplyr")

df <- tibble(
 Century = c(1, 2, 3, 4, 5), 
 CenturyLabel = c("1st", "Bit later", "", "", "Post-Roman"), 
 Value = c(.2, .3, 0, 0, .4) )

df$CenturyFactor <- factor(df$Century, labels = df$CenturyLabel), ordered = TRUE)

You can then use CenturyFactor as x-axis variable and you'll see a gap with any correct plotting libraries... With the big caveat that any duplicate labels cause the centuries to be merged!

One way around this is to plot Century (1 to 5) but tweak the labels to show CenturyLabel. This will be library-specific. No factors needed.

Using ggplot2:

library("ggplot2")

ggplot(df, aes(x = Century, y = Value)) +
  geom_col() +
  scale_x_continuous(labels = df$CenturyLabel, breaks = df$Century)

Plot with gaps

asachet
  • 6,620
  • 2
  • 30
  • 74
  • Actually the duplicate labels are merged into one factor level. So that's not fully working. I can't manage off the top of my head, at least not without setting the x labels explicitly which is not very elegant. – asachet Jun 10 '19 at 16:11
  • For this solution to work, you must not have duplicate labels. In your example, centuries 3 and 4 are merged into one factor level because they both have `""` as label. – asachet Jun 10 '19 at 16:18
  • Thank you, though pity about the duplicates; how would I set the x labels explicitly? – James Bejon Jun 10 '19 at 16:25