2017-06-06 22 views
1
  ggplotRegression <- function (fit) { 

      require(ggplot2) 

      ggplot(fit$model, aes_string(x = names(fit$model)[2], y = 
      names(fit$model)[1])) + 
      geom_point() + 
      stat_smooth(method = "lm", col = "red") + 
      labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 
       5), 
        "Intercept =",signif(fit$coef[[1]],5), 
        " Slope =",signif(fit$coef[[2]], 5), 
        " P =",signif(summary(fit)$coef[2,4], 5))) 

}如何在ggplot2的同一个图中添加不同分位数的不同图例?

   taus <-c(0.05 , 0.25, 0.50 , 0.75, 0.90 , 0.95) 

       m <- ggplotRegression(lm(formula = BMI ~ height_in_m 
        +weight_in_kg+ Highest_Education_level + 
        wealth_index + age_in_year_groups, data = dat_new)) 

      m+geom_quantile(quantiles=taus, lwd=1.5 , col="green4", 
      fill=taus) 

enter image description here

现在我想添加特定的颜色为每个分位数并添加spcific传说每个位数。

回答

1

许多ggplot统计让您使用封闭在..计算,例如用geom_density您可以在aes使用..count..的结果。

随着geom_quantile可以使用..quantile..

df <- data_frame(x = rnorm(100), y = rnorm(100)) 
ggplot(df, aes(x, y)) + 
    geom_point() + 
    geom_quantile(aes(colour = as.factor(..quantile..))) 

关键是要找出这些变量叫什么。需要计算统计量的Geoms(如geom_quantilegeom_density)具有相关联的ggproto对象,例如StatQuantileStatDensity,它具有用于计算代码compute_group的元素。

StatQuantile$compute_group最后的命令是

plyr::ldply(quantiles, quant_pred, data = data, method = method, 
    formula = formula, weight = weight, grid = grid, method.args = method.args) 

这里的功能,quant_pred - 你可以看到ggplot2:::quant_pred,返回一个列表。此列表的组件,包括quantile,可用于aes

相关问题