plot polynomial regression line with ggplot stat_smooth

懵懂的女人 提交于 2021-02-20 19:05:21

问题


I'm trying to create a scatter plot with second degree polynomial regression line using ggplot:stat_smooth. Here are the codes:

df.car_spec_data <- read.csv(url("http://www.sharpsightlabs.com/
wp- content/uploads/2015/01/auto-snout_car-specifications_COMBINED.txt"))

df.car_spec_data$year <- as.character(df.car_spec_data$year)

df.car_spec_data %>% group_by(year) %>%
summarise(maxspeed=max(top_speed_mph,
na.rm=T)) %>%  ggplot(aes(x=year, y=maxspeed,
group=1))+geom_point(color='red',   alpha=0.3,
size=3)+stat_smooth(method='lm', y~poly(x,2))

I got the following error message:

Error: Mapping must be created by `aes()` or `aes_()`

Thanks a lot.


回答1:


This works (for mtcars dataset):

df.car_spec_data <- mtcars
df.car_spec_data %>% group_by(cyl) %>%
  summarise(maxmpg=max(mpg, na.rm=T)) %>%  
    ggplot(aes(x=cyl, y=maxmpg, group=1)) + 
    geom_point(color='red',   alpha=0.3,size=3)+
    stat_smooth(method='lm', formula = y~poly(x,2))



来源:https://stackoverflow.com/questions/40003508/plot-polynomial-regression-line-with-ggplot-stat-smooth

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