mrad
mrad

Reputation: 303

Redistribute columns along x axis using ggplot2

Using this code:

ggplot(total_reads, aes(x=Week, y=Reads)) +
    geom_bar(position = "dodge", stat = "identity") +
    scale_y_log10(breaks=breaks, minor_breaks=minor_breaks) +
    scale_x_continuous() +
    facet_grid(~PEDIS, scales="free_x", space = "free_x") +
    theme_classic() +
    ylab("Total Bacterial Reads")

I produced this graph:

enter image description here

How do I remove the empty spaces in the first facet (pedis1) and make sure only the relevant labels are on the x axis (ie 0,3,6,12,13)?

Upvotes: 0

Views: 88

Answers (1)

chemdork123
chemdork123

Reputation: 13843

The quick answer is because your x axis values (total_reads$Week) is an integer/number. This automatically sets the scale to be continuous and therefore you have spacing according to the distance on the scale (like any numeric scale). If you want to have the bars right next to one another and remove the white space, you'll need to set the x axis to a discrete variable when plotting. It's easiest to do this by mapping factor(Week) right in the aes() declaration.

Here's an example with that modification as well as some other suggestions described below:

total_reads <- data.frame(
  Week=c(0,3,6,12,13),
  Reads=c(100,110,100,129,135),
  PEDIS=c(rep('PEDIS1', 3), rep('PEDIS2',2))
)

ggplot(total_reads, aes(x=factor(Week), y=Reads)) +
  geom_col() +
  facet_grid(~PEDIS, scales="free_x", space="free_x") +
  theme_classic()

enter image description here

A few other notes on what you see changed here:

  • Use geom_col(), not geom_bar(). If you check out the documentation associated with the geom_bar() function, you can see it mentions that geom_bar() is used for showing counts of observations along a single axis, whereas if you want to show value, you should use geom_col(). You get the same effect with geom_col() as if you use geom_bar(stat="identity").

  • Remove scale_x_continuous(). Not sure why you have this there anyway, but if your column Week is numeric, it would default to use this scale anyway. If you do use the sale, you will ask ggplot to force a continuous scale - apparently not what you want here.

Upvotes: 1

Related Questions