This is a follow-up to my question at ggplot2: Adding secondary transformed x-axis on top of plot, where I am using an axis from one plot as the top axis on another plot. The problem is that the ticks and grids of those 2 plots don't align with eachother, so using the axis (and associated grid and data) of one plot on the top of the other means that the bottom axis doesn't match the grid.
I've come upon a workaround, but it requires first constructing a plot where the x-axis ticks don't match the grid lines. I can define where the grids and ticks should be, but can't figure out how to plot such a thing. I am hoping someone can tell me what I am doing wrong.
I realize that the grid and tick marks must align in ggplot, but I've come across another post at How can I add a background grid using ggplot2? that gives a solution that is very close to what I need.
Following that solution, I can remove the grid and use geom_segment
to plot a "grid":
pts <- data.frame(x=c(170, 170, 170, 170, 177.5, 185),
y=c(-35, -25, -15, -35, -35, -35),
xend=c(185, 185, 185, 170, 177.5, 185),
yend=c(-35, -25, -15, -15, -15, -15))
ggplot(quakes, aes(long, lat)) + geom_point(shape = 1) +
geom_segment(data=pts, aes(x, y, xend=xend, yend=yend), color="white") +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
However, in that example the created grid lines don't look like a real grid because they don't extend to the edge of the plot. To make them look like real grid lines, I would need them to extend to the edge of the plot. I was thinking I could define pts
that lie outside the plot so that lines drawn between the pts
would extend to the edge. For example,
pts <- data.frame(x=c(170, 170, 170, 170, 177.5, 185),
y=c(-35, -25, -15, -35, -35, -35),
xend=c(185, 185, 185, 170, 177.5, 185),
yend=c(-35, -25, -15, -15, -15, -15))
ggplot(quakes, aes(long, lat)) + geom_point(shape = 1) + scale_x_continuous(limits=c(172.5, 182.5)) +
scale_y_continuous(limits=c(-30, -20)) +
geom_segment(data=pts, aes(x, y, xend=xend, yend=yend), color="white") +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
However, since the points are outside the plot, ggplot removes the missing values and doesn't plot the lines. Can anyone tell me if there is a way to make this work? Or, can anyone tell me if there is a better way to do what I'm trying to do?
Thanks!!!