37

I am trying to replicate the example here (sthda.com) using the following code:

# Change point shapes and colors manually
ggplot(mtcars, aes(x=wt, y=mpg, color=cyl, shape=cyl)) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
  scale_shape_manual(values=c(3, 16, 17))+ 
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  theme(legend.position="top")

The example on that web page says that code should produce the following result:

plot

But when I run it in R, I get the following error:

"Error: Continuous value supplied to discrete scale"

Does anyone know what could be wrong with this code? Or why I am getting a different result than the example?

If someone could run the sample code and tell me if they get the same error I would be very grateful.

rawr
  • 20,481
  • 4
  • 44
  • 78
Katherine Hepworth
  • 375
  • 1
  • 3
  • 4

2 Answers2

42

Yeah, I was able to fix it by converting the color and shape aesthetics to factors:

ggplot(mtcars, aes(x=wt, y=mpg, color=as.factor(cyl), shape=as.factor(cyl))) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
  scale_shape_manual(values=c(3, 16, 17))+ 
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  theme(legend.position="top")
lauren.marietta
  • 2,125
  • 1
  • 11
  • 19
Jonathan Hill
  • 1,745
  • 15
  • 25
  • 19
    Please also mention what you changed. Otherwise everyone would need to spend time on going through both codes and trying to find differences. You added `as.factor` to `color` and `shape`. – PM0087 Jun 25 '20 at 16:01
17

as.factor makes it work

ggplot(mtcars, aes(x=wt, y=mpg, color=as.factor(cyl), shape=as.factor(cyl))) +
  geom_point() + 
  geom_smooth(method=lm, se=FALSE, fullrange=TRUE)+
  scale_shape_manual(values=c(3, 16, 17))+ 
  scale_color_manual(values=c('#999999','#E69F00', '#56B4E9'))+
  theme(legend.position="top")
Andrew Lavers
  • 4,328
  • 1
  • 12
  • 19