Search code examples
rggplot2bar-chartaxisspacing

How to increase space between axis line and bars in a bar plot using ggplot2


How could I increase the space between the y-axis line and the first bar in the following bar plot?

# Load ggplot
library(ggplot2)

# Load the Titanic dataset
data("Titanic")
Titanic <- as.data.frame(Titanic)

# Bar plot
ggplot(Titanic, aes(x = Class, y = Freq, fill = Survived)) + 
  geom_col(position = "fill") +
  coord_cartesian(ylim = c(0, 1), expand = FALSE) +
  theme_classic() +
  theme(legend.position = "none",
        axis.line.x = element_blank(),
        axis.ticks.x = element_blank())

Is there a way to apply coord_cartesian(expand = FALSE) only to the x-axis? This could resolve the problem.

enter image description here


Solution

  • I don't think you can get that level of control with coord_cartesion. You can use the scales instead

    ggplot(Titanic, aes(x = Class, y = Freq, fill = Survived)) + 
      geom_col(position = "fill") +
      scale_x_discrete(expand=expansion(add=c(.8, 0))) + 
      scale_y_continuous(expand=expansion(add=c(0, 0))) + 
      theme_classic() +
      theme(legend.position = "none",
            axis.line.x = element_blank(),
            axis.ticks.x = element_blank())
    

    Change the value of .8 to whatever you like.

    enter image description here