Paul Z Paul Z - 2 months ago 10
R Question

Continuous position scales with no effect on the spacing between the bar and the x axis in ggplot2 with R

I am designing a bar plot with

ggplot2
package.
The only problem is that I cannot get rid of the space between the bars and the x-axis.
I know that this formula should resolve the problem:

scale_y_continuous(expand = c(0, 0)) function


But it seems that the element for the error bar is overwriting it and gives always this space.

here my code:

p<-ggplot(data=tableaumergectrlmut, aes(x=ID, y=meanNSAFbait, fill=Condition)) +
geom_bar(stat="identity", position=position_dodge())+
scale_y_continuous(expand = c(0,0))+
geom_errorbar(aes(ymin=meanNSAFbait-SDNSAFbait,
ymax=meanNSAFbait+SDNSAFbait, width=0.25), position=position_dodge(.9))

Answer

Using some example data to generate a plot that (I think) shows the problem you're having.

library(ggplot2)

df <- data.frame(val = c(10, 20, 100, 5), name = LETTERS[1:4])

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity")

enter image description here

There is a gap from the zero point on the y axis (bottom of the bars) and where the x axis labels are.

You can remove this using scale_y_discrete or scale_y_continuous, depending on the nature of your data, and setting expand to c(0,0):

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  scale_y_discrete(expand = c(0,0)) + 
  scale_x_discrete(expand = c(0,0))

This gives the plot:

enter image description here

Note I've also removed the gap along the y axis, simply remove the scale_x_discrete line to add this gap back in.

Since error bars are an issue, here are a few examples:

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = val - 10,
                    ymax = val + 10))

enter image description here

You can use scale to remove the padding down to the error bar:

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = val - 10,
                    ymax = val + 10)) +
  scale_y_continuous(expand = c(0,0))

enter image description here

Or you can use coord_cartesian to give a hard cutoff:

ggplot(df, aes(x = name, y = val, fill = name)) +
  geom_bar(stat = "identity") +
  geom_errorbar(aes(ymin = val - 10,
                    ymax = val + 10)) +
  scale_y_continuous(expand = c(0,0)) +
  coord_cartesian(ylim = c(0, max(df$val) + 10))

enter image description here