Stencil
Stencil

Reputation: 125

Use both alpha and stat_smooth in ggplot2

I'm attempting to apply alpha to a smoothed line in the most recent version of ggplot2. I have a plot that was broken in the December update. Toy example of that plot:

dat <- mtcars
library(dplyr)
library(ggplot2)
plotdat <- dat %>% group_by(hp) %>% summarise(ave = mean(wt))
ggplot(plotdat, aes(hp,ave)) +
  geom_line(size = 2, alpha = .2) +
  geom_line(size = 2, alpha = .2, stat = "smooth")
#Warning message:
#Computation failed in `stat_smooth()`:
#object 'auto' of mode 'function' was not found 

The above code worked in past versions, but now throws a warning. Of course using the geom_smooth approach does not allow you to access alpha for the smoothed line, because the alpha command controls the ribbon.

ggplot(plotdat, aes(hp,ave)) +
  geom_line(size = 2, alpha = .1) +
  geom_smooth(size = 2, se = FALSE, alpha = .1)

Produces a plot close to what I want. How can I produce the dark blue smoothed line with alpha / transparency?

(Note that the second alpha is not taking effect.)

enter image description here

Upvotes: 2

Views: 1706

Answers (1)

Stencil
Stencil

Reputation: 125

Thanks to @aosmith for the suggestion. I was able to get a working answer by directly specifying the method as "loess" in geom_line.

dat <- mtcars
library(dplyr)
library(ggplot2)
plotdat <- dat %>% group_by(hp) %>% summarise(ave = mean(wt))
ggplot(plotdat, aes(hp,ave)) +
  geom_line(size = 2, alpha = .2) +
  geom_line(size = 2, alpha = .2, stat = "smooth", method = "loess")

Upvotes: 1

Related Questions