I am aware ggplot by default puts 'padding' between the axes and the data. I wish for the origin of the axes to be an actual number, e.g. 0. I know this can be done using scale_y_continuous(expand = c(0, 0))
and scale_x_continuous(expand = c(0, 0))
, however without the 'padding' the tick marks do not align correctly with the panel borders. It is as if they are not positioned correctly.
Consider this using mtcars data:
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
scale_y_continuous(expand = c(0, 0), breaks = seq(0, 5, by = 1), limits = c(0, 5)) +
scale_x_continuous(expand = c(0, 0), breaks = seq(10, 35, by = 5), limits = c(10, 35))
This returns a plot without padding, but you cannot really make out the misalignment yet because the panel border is white.
Now, plot this (panel border has been defined):
p +
theme(
panel.border = element_rect(size= 1, fill=NA),
axis.ticks = element_line(size = 1, colour ="black"))
The tick at the top of the y axis and the tick at the right of the x axis are not aligned. It is now clear because the panel border is black. I thought perhaps I could mess around with the thickness of the ticks but it does not help. I also thought it was something to do with the major and minor lines of the panel but the following doesn't make a difference:
p +
theme(
panel.border = element_rect(size= 1, fill=NA),
axis.ticks = element_line(size = 1, colour ="black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
Interestingly, if I remove the panel border and instead add in a defined x and y axis line it does look a bit better because it's harder to see the misalignment unless you really zoom in:
p +
theme(
axis.line.x = element_line(size = 0.5, linetype = "solid", colour = "black"),
axis.line.y = element_line(size = 0.5, linetype = "solid", colour = "black"),
axis.ticks = element_line(size = 0.5, colour ="black"),
panel.border = element_blank())
I am not satisfied with the answer given in Tick marks misaligned with panel in ggplot2 [R] and think there must be a way around this?
Any thoughts? I am missing something here...