R weird behavior with geom_abline() - r

I am using this code:
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1) +
geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed')
And I get this graph:
Then I comment out the middle line of code with command + shift + c
ggplot(mtcars, aes(x = wt, y = mpg)) +
# geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1) +
geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed')
I get a graph without any lines. Where did the line from geom_abline() go?
I then switch the order and be careful with the + signs...
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed') +
geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1)
Both lines are back. So the code for geom_abline() seemed fine, right?
So I then comment out the middle line:
ggplot(mtcars, aes(x = wt, y = mpg)) +
# geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed') +
geom_smooth(method = "lm", se = FALSE, color = '#376795', size = 1)
The geom_smooth() is there but not the abline. I'm really confused by this behavior. I really just want the abline and not the smooth but this doesn't work:
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed')
There must be a simple reason. But also - why is the behavior inconsistent? It feels like a bug because the same code in one place seems to work and in another place doesn't.

You can use this code to plot only the abline:
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_blank() +
geom_abline(intercept = 34.232237, slope = -4.539474, linetype = 'dashed')
Output:

Related

Override legend for linechart with points

My current legend displays the shapes of the points in the chart, crossed out by the line. Id like to remove this line in the legend and just display the shapes.
The code looks like this:
p <- ggplot(data=cumdf, aes(x=quarters2)) +
geom_line(aes(y = mean_cumsum, colour='Platform participants'), size = 1.5)+
geom_point(aes(y = mean_cumsum, colour='Platform participants', shape='Platform participants'), size=3) +
geom_line(aes(y = mean_interventions, colour='Actions'), size=1.5) +
geom_point(aes(y = mean_interventions, colour='Actions', shape='Actions'), size=3) +
geom_line(aes(y = mean_sales, colour="Adopters"), size=1.5) +
geom_point(aes(y = mean_sales, colour='Adopters', shape='Adopters'), size=3) +
xlab("Quarters") +
ylab("Cumulative occurences") +
scale_shape_manual("", values=c("Platform participants" = 16, "Actions" = 17, "Adopters"=15)) +
scale_colour_manual("",breaks = c("Platform participants", "Actions", "Adopters"),
values = c ("#C80000", "#696969", "#4E33FF")) +
theme_stata(base_size = 15, base_family = "sans", scheme = "s2color") +
scale_x_continuous(n.breaks=14) +
geom_vline(xintercept=3, linetype='dashed', size=1.7)
p
Add show.legend to your geom_line. Since you have multiple calls to geom_line, you need to add it to all of them.
I'll demonstrate using mtcars, updated for a factor.
dat <- transform(mtcars, cyl = factor(cyl))
Before the change:
ggplot(dat, aes(mpg, disp, group = cyl, color = cyl, shape = cyl)) +
geom_line() +
geom_point()
Add show.legend=FALSE:
ggplot(dat, aes(mpg, disp, group = cyl, color = cyl, shape = cyl)) +
geom_line(show.legend = FALSE) +
geom_point()
The answer was found in the comments, by adding show.legend=FALSE to geom.line() .

multiple kernal densities in ggplot2

I would like to add a kernel density estimate for 2 types of data to a ggplot. If I use the following code, it displays a kernel density estimate for the 2nd factor level only. How do I get a kernel density estimate for both factor levels (preferably different colors)?
ggplot(mtcars, aes(x = disp, y=mpg, color=factor(vs))) +
theme_bw() +
geom_point(size=.5) +
geom_smooth(method = 'loess', se = FALSE) +
stat_density_2d(geom = "raster", aes(fill = ..density.., alpha = ..density..), contour = FALSE) +
scale_alpha(range = c(0,1)) +
guides(alpha=FALSE)
One approach is to use two stat_density_2d layers with subsets of the data and manually color them. It is not exactly what you are after but with tweaking it can be solid:
ggplot(mtcars, aes(x = disp, y=mpg, color=factor(vs))) +
theme_bw() +
geom_point(size=.5) +
geom_smooth(method = 'loess', se = FALSE) +
stat_density_2d(data = subset(mtcars, vs == 0), geom = "raster", aes(alpha = ..density..), fill = "#F8766D" , contour = FALSE) +
stat_density_2d(data = subset(mtcars, vs == 1), geom = "raster", aes(alpha = ..density..), fill = "#00BFC4" , contour = FALSE) +
scale_alpha(range = c(0, 1))
This might do what you want :
```
ggplot(mtcars, aes(x = disp, y=mpg, color=factor(vs))) +
theme_bw() +
geom_point(size=.5) +
geom_smooth(method = 'loess', se = FALSE) +
stat_density_2d(data = subset(mtcars, vs==1), geom = "raster", fill='blue', aes(fill = ..density.., alpha = ..density..), contour = FALSE) +
scale_alpha(range = c(0,0.8)) +
stat_density_2d(data = subset(mtcars, vs==0), geom = "raster", fill='red', aes(fill = ..density.., alpha = ..density..), contour = FALSE) +
guides(alpha=FALSE)
```
Another potential solution that I discovered in this post is to use geom="tile" in the stat_density2d() call instead of geom="raster".
ggplot(mtcars, aes(x = disp, y=mpg, color=factor(vs))) +
theme_bw() +
geom_point(size=.5) +
geom_smooth(method = 'loess', se = FALSE) +
stat_density_2d(geom = "tile", aes(fill = factor(vs), alpha = ..density..), contour = FALSE, linetype=0) +
scale_alpha(range = c(0,1))

Add regression line legend to geom_abline

I've coded this:
ggplot() +
geom_point(mapping = aes(x = X, y = y)) +
geom_abline(intercept = -0.9930872, slope = 0.4866284, colour = "red") +
geom_abline(intercept = -1, slope = 0.5, colour = "blue")
but cannot seem to get a working legend for my least square and populuation regression line. I've tried various stack overflow answers but nothing seems to give me what I need.
Add a legend to a ggplot2 scatter plot including additional lines
This looked like the best answer, but I can't get it to work!
Any suggestions?
set.seed(1234)
X <- rnorm(20,sd=2.5)
y <- -1+0.5*X+rnorm(20, sd=0.4)
library(ggplot2)
ggplot() +
geom_point(mapping = aes(x = X, y = y)) +
geom_abline(aes(intercept = -0.9930872, slope = 0.4866284, colour = "line1"), lwd=1) +
geom_abline(aes(intercept = -1, slope = 0.5, colour = "line2"), lwd=1) +
scale_colour_manual(values=c("line1"="red","line2"="blue"))
With slight modification your code works just fine:
ggplot() +
geom_point(mapping = aes(x = X, y = y)) +
geom_abline(aes(colour = "line_1", intercept = -0.9930872, slope = 0.4866284)) +
geom_abline(aes(colour = "line_2", intercept = -1, slope = 0.5)) +
scale_colour_manual(name = "lines", values = c("red", "blue")) +
theme(legend.position = "bottom")
Added legend position in case if you want to change that aswell.

Adding uncertainty bands to a smooth spline in a scatterplot

I have a following scatterplot with a smooth spline
a<-rep(1:50,len=500)
b<-sample(0:5000,500)
c<-round(seq(0,600,len=500))
data_frame<-as.data.frame(cbind(a,b,c))
names(data_frame)<-c("ID","toxin_level","days_to_event")
plot(data_frame$days_to_event,data_frame$toxin_level, xlim=c(600,0),xlab="days before the event",ylab="Toxin level",type="p")
abline(v=0,col="red")
x <- data_frame$days_to_event
y <- data_frame$toxin_level
fit.sp = smooth.spline(y ~ x, nknots=20)
lines(fit.sp, col="blue")
This is the resulting plot
I was wondernig if it is possible to somehow add confidence bands to this curve? I deally I would like it to be in a transparent blue, but any color including gray is OK.
Updated: using scale_x_reverse to match your graph more precisely...
How about this using ggplot2?
library(ggplot2)
ggplot(data_frame, aes(x = days_to_event, y = toxin_level)) + geom_point() +
geom_vline(xintercept = 0, color = "red") + scale_x_reverse() +
xlab("Days before the event") + ylab("Toxin Level") +
geom_smooth(method = lm, se = TRUE)
Which gives this:
Or to match your question a bit more:
ggplot(data_frame, aes(x = days_to_event, y = toxin_level)) + geom_point(shape = 1) +
geom_vline(xintercept = 0, color = "red") + scale_x_reverse() +
xlab("Days before the event") + ylab("Toxin Level") +
geom_smooth(method = lm, se = TRUE, color = "blue", fill = "lightblue") +
theme_bw()

Drawing only boundaries of stat_smooth in ggplot2

When using stat_smooth() with geom_point is there a way to remove the shaded fit region, but only draw its outer bounds? I know I can remove the shaded region with something like:
geom_point(aes(x=x, y=y)) + geom_stat(aes(x=x, y=y), alpha=0)
but how can I make the outer bounds of it (outer curves) still visible as faint black lines?
You can also use geom_ribbon with fill = NA.
gg <- ggplot(mtcars, aes(qsec, wt))+
geom_point() +
stat_smooth( alpha=0,method='loess')
rib_data <- ggplot_build(gg)$data[[2]]
ggplot(mtcars)+
stat_smooth(aes(qsec, wt), alpha=0,method='loess')+
geom_point(aes(qsec, wt)) +
geom_ribbon(data=rib_data,aes(x=x,ymin=ymin,ymax=ymax,col='blue'),
fill=NA,linetype=1)
...and if for some reason you don't want the vertical bars, you can just use two geom_line layers:
ggplot(mtcars)+
stat_smooth(aes(qsec, wt), alpha=0,method='loess')+
geom_point(aes(qsec, wt)) +
geom_line(data = rib_data,aes(x = x,y = ymax)) +
geom_line(data = rib_data,aes(x = x,y = ymin))
There are most likely easier ways, but you may try this as a start. I grab data for the confidence interval with ggbuild, which I then use in geom_line
# create a ggplot object with a linear smoother and a CI
library(ggplot2)
gg <- ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm")
gg
# grab the data from the plot object
gg_data <- ggplot_build(gg)
str(gg_data)
head(gg_data$data[[2]])
gg2 <- gg_data$data[[2]]
# plot with 'CI-lines' and the shaded confidence area
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm", se = TRUE, size = 1) +
geom_line(data = gg2, aes(x = x, y = ymin), size = 0.02) +
geom_line(data = gg2, aes(x = x, y = ymax), size = 0.02)
# plot with 'CI-lines' but without confidence area
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, size = 1) +
geom_line(data = gg2, aes(x = x, y = ymin), size = 0.02) +
geom_line(data = gg2, aes(x = x, y = ymax), size = 0.02)

Resources