0
votes

I want my tick marks/gridlines to be on the very edge of the plot border.

What I want: Drawn graph with leftmost and rightmost tick marks on the borders

What it looks like: GGPlot graph with leftmost and rightmost tick marks NOT on the borders

Code used to create the above:

data <- data.frame(
  year = seq(1998,2018),
  soc = runif(21,1,90)
)

ggplot(data, aes(x = year, y=soc)) +
  geom_line(data=data) +
  xlim(c(1995,2020)) +
  theme_bw() +
  theme(panel.grid.major = element_line(colour="gray", size=0.5))

This question doesn't correctly address the problem - I am not looking to fit the axis limits to the minimum and maximum of my data points, but rather to make sure that the tick marks land perfectly on the border of the graph.

1

1 Answers

1
votes

You can remove the extra plot area by setting expand=FALSE in coord_cartesian. I then modified the plot margin so that the rightmost number doesn't get cut off.

ggplot(data, aes(x = year, y=soc)) +
  geom_line(data=data) +
  scale_x_continuous(limits = c(1995,2020)) +
  theme_bw() +
  theme(panel.grid.major = element_line(colour="gray", size=0.5)) +
  coord_cartesian(expand = F)+
  theme(plot.margin = margin(6,10,6,6))

enter image description here