I'd like to make a density plot so that the axes are right next to (or at least very close to) the tick marks. As seen in this MWE, ggplot2
reserved some space between the tick marks and the axes in both the x- and the y-axis, even when I have specified the xlim
and ylim
. How can I remove them?
With other kinds of plots, it seems like you can call something like scale_y_continuous(limits=c(0, 100), expand = c(0, 0))
(for example), but calling scale_linetype_manual()
with these parameters doesn't seem to do anything.
Also note that in the note here I am drawing the axes using geom_segment
. Is there a better way to do this?
set.seed(0) the.df <- data.frame( x = rnorm(800, 50, 10), group = rep(letters[1:8], each = 100)) p <- ggplot(the.df) + stat_density(aes(x = x, linetype = group), geom = "line", position = "identity") + xlim(10, 90) + ylim(0, 0.06) + scale_linetype_manual(values = c("11", "12", "13", "14", "21", "22", "23", "24")) + geom_segment(aes(x = 10, y = 0, xend = 90, yend = 0)) + geom_segment(aes(x = 10, y = 0, xend = 10, yend = 0.06)) p
You can use the xlim() and ylim() functions to set the x-axis limits and y-axis limits of plots in R.
ylim( limits ) sets the y-axis limits for the current axes or chart. Specify limits as a two-element vector of the form [ymin ymax] , where ymax is greater than ymin .
The xlim() function with the provided parameters as the range of the y-axis in vectors is used to set the y-axis without dropping any data of the given plot or an object accordingly. Syntax: xlim(...) Parameters: …: if numeric, will create a continuous scale, if factor or character, will create a discrete scale.
Turns out scale_x_continuous()
and scale_x_continuous
do work. I just didn't use them correctly.
set.seed(0) the.df <- data.frame( x = rnorm(800, 50, 10), group = rep(letters[1:8], each = 100)) p <- ggplot(the.df) + stat_density(aes(x = x, linetype = group), geom = "line", position = "identity") + scale_linetype_manual(values = c("11", "12", "13", "14", "21", "22", "23", "24")) + scale_x_continuous(limits=c(10, 90), expand = c(0, 0)) + scale_y_continuous(limits=c(0, 0.06), expand = c(0, 0)) + geom_segment(aes(x = 10, y = 0, xend = 90, yend = 0)) + geom_segment(aes(x = 10, y = 0, xend = 10, yend = 0.06)) p
Another option using coord_cartesian
instead of continuous position scales (x & y):
set.seed(0) the.df <- data.frame( x = rnorm(800, 50, 10), group = rep(letters[1:8], each = 100)) p <- ggplot(the.df) + stat_density(aes(x = x, linetype = group), geom = "line", position = "identity") + scale_linetype_manual(values = c("11", "12", "13", "14", "21", "22", "23", "24")) + geom_segment(aes(x = 10, y = 0, xend = 90, yend = 0)) + geom_segment(aes(x = 10, y = 0, xend = 10, yend = 0.06))+ coord_cartesian(xlim = c(10, 90), ylim = c(0, .06), expand = FALSE) p
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