Standard R plots does not set the origin of the x and y axis at zero. To reset this parameter so that the origin of the plot is fixed at 0,0 simply use the xaxs and yaxs parameters. Here is a description from the R graphical parameters help page. The style of axis interval calculation to be used for the x-axis.
Let's start with the ylim() function. It specifies the upper and lower limit of the y-axis. It is a fundamental function and can be used inside the ggplot() , plot() , and other plot functions as a parameter.
You can use the xlim() and ylim() functions to set the x-axis limits and y-axis limits of plots in R.
xlim
and ylim
don't cut it here. You need to use expand_limits
, scale_x_continuous
, and scale_y_continuous
. Try:
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0))
You may need to adjust things a little to make sure points are not getting cut off (see, for example, the point at x = 5
and y = 5
.
Simply add these to your ggplot:
+ scale_x_continuous(expand = c(0, 0), limits = c(0, NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(df, aes(x, y)) + geom_point()
p <- p + expand_limits(x = 0, y = 0)
p # not what you are looking for
p + scale_x_continuous(expand = c(0, 0), limits = c(0,NA)) +
scale_y_continuous(expand = c(0, 0), limits = c(0, NA))
Lastly, take great care not to unintentionally exclude data off your chart. For example, a position = 'dodge'
could cause a bar to get left off the chart entirely (e.g. if its value is zero and you start the axis at zero), so you may not see it and may not even know it's there. I recommend plotting data in full first, inspect, then use the above tip to improve the plot's aesthetics.
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
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