mtcars ggplot doesn't know how to deal with class numeric

后端 未结 2 1485
[愿得一人]
[愿得一人] 2021-01-21 05:33

I am just trying to make a simple plot using mtcars and ggplot:

ggplot(data=mtcars, aes(x=mpg,y=hp))+geom_line(mpg,hp,col=cyl)

but I get the er

相关标签:
2条回答
  • 2021-01-21 05:35

    My suggestion is to specify all aesthetics in one place and to coerce cyl to factor for colour coding as categorial variable.

    ggplot(data=mtcars, aes(x=mpg, y=hp, colour=factor(cyl))) + geom_line()
    

    will create

    0 讨论(0)
  • 2021-01-21 05:53

    See if you get better results passing hte argument to aes inside geom_line:

    ggplot(data=mtcars, aes(x=mpg,y=hp))+geom_line(aes(x=mpg,y=hp,colour=cyl) )
    

    I think the results are a bit clearer if you add a grouping parameter to the basic aes spec:

    ggplot(data=mtcars, aes(x=mpg,y=hp, group=cyl)) + 
            geom_line(aes(x=mpg,y=hp,colour=cyl) )
    

    And even better legend anotation with a factor() on cyl:

    ggplot(data=mtcars, aes(x=mpg,y=hp, group=cyl))+ 
           geom_line(aes(x=mpg,y=hp,col=factor(cyl)) )
    
    0 讨论(0)
提交回复
热议问题