This question is not about controlling the axis limits (I think), but rather about controlling the lengths of the axes lines themselves. I'm trying to make a ggplot (so that I can make use of its nice facetting capabilities) that is similar to a base R plot where the axes are manually added. These axes only extend as far as the last axis label.
Some setup data and the base R type of plot I'm trying to mimic:
library("ggplot2")
library("cowplot")
library("grid")
set.seed(5)
x <- rnorm(10)
y <- rnorm(10)
D <- data.frame(x, y)
plot(x, y, axes = FALSE)
axis(1)
axis(2)
ggplot(D, aes(x, y)) +
geom_point()
The default changes to ggplot from the cowplot
package get pretty close:
But how can I tell ggplot to only draw the lines as far as the last axis label, even though points lie outside of that value (as in the base R plot)?
Well, @Gregor posted his comment while I was working on this, so here's the implementation. Just for illustrative purposes, the annotated axes are rendered in red to make it obvious they were added separately from the standard axis lines. If you're going to make a bunch of plots like this, you can also add some logic to programmatically determine the x and y limits for annotate
and coord_cartesian
.
my_theme = list(theme_bw(),
theme(panel.border=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank()),
labs(y="",x=""))
ggplot(D, aes(x,y)) +
geom_point() +
coord_cartesian(xlim=c(-1.4,1.4), ylim=c(-2.4,1.4)) +
my_theme +
annotate(x=-1.4, xend=-1.4, y=-2, yend=1, colour="red", lwd=0.75, geom="segment") +
annotate(x=-1, xend=1, y=-2.4, yend=-2.4, colour="red", lwd=0.75, geom="segment")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With