My data range always seems to be greater than the top label in the y-axis. Is there a way I can automatically include it without manually setting limits?
e.g. in
Maybe with scale_y_continuous
and the expand
argument:
ggplot(data.frame(x=1:10, y=c(11:17,5:3)), aes(x,y)) +
geom_point() +
scale_y_continuous(expand=c(0.5, 0.5))
So I don't think expand
is actually the way to go about this, rather expand_limits
.
This is clearly not the most beautiful code, but this is basically the functionality I'm looking for where the labels on the y-axis encompass the data completely.
dat<-data.frame(x=1:10, y=c(11:17,5:3))
ggplot(dat, aes(x,y)) +
geom_point() +
expand_limits(y=c(min(pretty(c(dat$y, min(dat$y) * (0.95)))), max(pretty(c(dat$y, max(dat$y) * (1.05))))))
I've assumed expand default as 0.05 and that pretty is used with defaults. Is there a better way to do this?
dat<-data.frame(x=1:10, y=c(11:17,5:3))
ggplot(dat, aes(x,y)) +
geom_point()+
scale_y_continuous(breaks=c(pretty(dat$y, n=4),18), expand=c(0.25, 0.25))
The pretty
function chooses nice breaks as 1, 2 or 5 times a power of 10. Then I just included 18 to that vector.
What about the following solution:
library(ggplot2)
d <- data.frame(x=1:11, y=c(11:17,5:2))
px <- pretty(d$x)
py <- pretty(d$y)
ggplot(d, aes(x,y)) + geom_point() +
scale_x_continuous(breaks=px, limits=range(px)) +
scale_y_continuous(breaks=py, limits=range(px))
Have you tried skipping the 0.95 * 1.05 multipliers?
expand_limits(y=c(min(pretty(c(dat$y,min(dat$y)))),max(pretty(c(dat$y,max(dat$y))))))