"Error: Continuous value supplied to discrete scale" in default data set example mtcars and ggplot2

103,153

Solution 1

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")

Solution 2

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")
Share:
103,153
Katherine Hepworth
Author by

Katherine Hepworth

Updated on December 17, 2020

Comments

  • Katherine Hepworth
    Katherine Hepworth over 3 years

    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.