0

I am trying to create a plot in ggplot with year on the x-axis, however, when I plot the data there is a gap between 2018 and 2020 data (I do not have data for 2019). I am looking for help on how to remove this gap. Thank you!

Here is my script:

p1<-ggplot(df1, aes(x=year, y=mean, fill=strata))+
  geom_bar(aes(y = mean), , position="dodge", stat="identity") +
  scale_x_continuous(labels=df1$year, breaks = df1$year)+
  geom_errorbar(aes(ymin=mean-se, 
                    ymax=mean+se), width=0.2,position=position_dodge(0.9 )) 
                                                                

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
Olivia
  • 23
  • 3
  • It would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Jan 09 '23 at 07:21

1 Answers1

0

The issue is that your year variable is a continuous variable. One option to remove the gaps resulting from years with missing data would be to convert your year column to a factor and of course get rid of scale_x_continuous.

As you provided no data I created a minimal reprex using some fake random example data.

First to reproduce your issue:

library(ggplot2)

set.seed(123)

df1 <- data.frame(
  year = c(2017:2018, 2020:2022),
  mean = runif(15, 5000, 20000),
  strata = rep(c("Lower", "Mid", "Upper"), each = 5)
)

ggplot(df1, aes(x = year, y = mean, fill = strata)) +
  geom_bar(aes(y = mean), , position = "dodge", stat = "identity") +
  scale_x_continuous(labels = df1$year, breaks = df1$year)

Second, converting to a factor and getting rid of scale_x_continuous gives the desired result with no gaps:

ggplot(df1, aes(x = factor(year), y = mean, fill = strata)) +
  geom_bar(aes(y = mean), , position = "dodge", stat = "identity")

stefan
  • 90,330
  • 6
  • 25
  • 51