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

做~自己de王妃 提交于 2019-11-27 23:31:39

问题


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:

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.


回答1:


Yeah, I was able to fix it with the following snippet:

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



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


来源:https://stackoverflow.com/questions/43359050/error-continuous-value-supplied-to-discrete-scale-in-default-data-set-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!