Rahi
Rahi

Reputation: 175

Use geom_smooth to create multiple lines from multiple criteria?

I am trying to create multiple smooth lines based on criteria 1 with same linetype and assign different colours to each line based on criteria 2. I looked through various similar questions (like this, this, this) in stackoverflow but they all worked on single criteria rather than two criteria. I tried different approaches but have not got the complete result. The different approaches and its result are as follows:

APPROACH I:

data(mtcars)
p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl))) +
  geom_point() + 
  geom_smooth( aes(group = as.factor(carb)),method ="lm", se = F, fullrange = T, alpha = .15, linetype = "dashed") 
p

The result is: enter image description here

The colours to the points is correct and single linetype. However, number of lines and colour are wrong. I want lines to have red, blue or green colour based on "cyl" value.

APPROACH II: The second approach I tried, gave me correct number of lines and colour but had different linetype for each line.

p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl), linetype = as.factor(carb))) +
  geom_point() + 
  geom_smooth( method ="lm", se = F, fullrange = T, alpha = .15) 
p

enter image description here

APPROACH III: In approach III, the results were similar to approach I.

p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl), group = as.factor(carb), linetype = "dashed")) +
  geom_point() + 
  geom_smooth( method ="lm", se = F, fullrange = T, alpha = .15) 
p

enter image description here

In nutshell, Approach II gets me closest to my objective. Now, how to get single linetype in Approach II?

Thanks in advance for any help!

Upvotes: 0

Views: 3122

Answers (1)

Duck
Duck

Reputation: 39595

I would suggest next approach, formating linetypes:

library(ggplot2)
#Data
data(mtcars)
#Plot
p <- ggplot(mtcars, aes(mpg, hp, colour = as.factor(cyl), linetype = as.factor(carb))) +
  geom_point() + 
  geom_smooth( method ="lm", se = F, fullrange = T, alpha = .15) 
p + scale_linetype_manual(values = rep('solid',length(unique(mtcars$carb))))

Output:

enter image description here

Upvotes: 4

Related Questions