AndrewGB
AndrewGB

Reputation: 16856

Increase width of ribbon when increasing size of linear model line in ggplot2

I am plotting a simple linear model with ggplot2. However, when I increase the size of the line, the ribbon does not change size (understandable). However, how would I scale the ribbon so that it matches the increase in line thickness?

Here is a simple example using the iris dataset:

library(ggplot2)

ggplot(iris, aes(x = Petal.Width, y = Sepal.Length)) + 
    geom_point() +
    stat_smooth(method = "lm", col = "red")

enter image description here

As you can see when you increase size (I'm over exaggerating the size here), then more of the ribbon is covered up.

ggplot(iris, aes(x = Petal.Width, y = Sepal.Length)) + 
    geom_point() +
    stat_smooth(method = "lm", col = "red", size = 5)

enter image description here

Essentially, the ribbon only needs to extend out as much as the additional thickness of the line that is displacing/obscuring the ribbon.

Expected Results

enter image description here

Upvotes: 1

Views: 228

Answers (1)

Jon Spring
Jon Spring

Reputation: 66835

Perhaps like this?

ggplot(iris, aes(x = Petal.Width, y = Sepal.Length)) + 
  geom_point() +
  stat_smooth(method = "lm", col = "red", size = 5, 
              aes(ymin = after_stat(y - 5*se),
                  ymax = after_stat(y + 5*se)))

enter image description here

Upvotes: 2

Related Questions