用ggplot stat_smooth绘制多项式回归线

时间:2016-10-12 16:17:24

标签: r ggplot2 dplyr

我尝试使用ggplot:stat_smooth创建具有二次多项式回归线的散点图。 以下是代码:

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

我收到以下错误消息:

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

非常感谢。

1 个答案:

答案 0 :(得分:3)

这适用于(对于mtcars数据集):

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

enter image description here