【问题标题】:Adding a regression line to a facet_grid with qplot in R在 R 中使用 qplot 将回归线添加到 facet_grid
【发布时间】:2023-04-01 16:13:01
【问题描述】:

我正在尝试向这个 facet_grid 添加一条回归线,但我似乎遇到了问题。

 qplot(date, data=ua, geom="bar", 
                      weight=count, 
                      ylab="New User Count", 
                      xlab='Date', 
                      main='New Users by Type Last 3 Months',
                      colour=I('lightgreen'),
                      fill=I('grey')) + 
    facet_grid(un_region~role, scales='free', space='free_y') + 
    opts(axis.text.x =theme_text(angle=45, size=5))

这是我正在处理的数据样本,注意计数需要相加,这就是我使用 weight=count 的原因,不确定是否有更好的方法。

     date         role                   name un_region              un_subregion us_state count
1 2012-06-21 ENTREPRENEUR              Australia   Oceania Australia and New Zealand              2
2 2012-06-21 ENTREPRENEUR                Belgium    Europe            Western Europe              1

谢谢。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不确定您在绘制什么斜率,因为您似乎使用的是条形图。你可以通过三种方式做到这一点,我将举例说明两种。如果您有实际的 xy 数据,并且想要按方面拟合各个回归线,只需使用 stat_smooth(method="lm")。这是一些代码:

    library(ggplot2)
    x <- rnorm(100)
    y <-  + .7*x + rnorm(100)
    f1 <- as.factor(c(rep("A",50),rep("B",50)))
    f2 <- as.factor(rep(c(rep("C",25),rep("D",25)),2))
    df <- data.frame(cbind(x,y))
    df$f1 <- f1
    df$f2 <- f2
    
    ggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+stat_smooth(method="lm",se=FALSE)
    

    这会产生:

    或者您可以使用geom_abline() 命令设置您自己的截距和斜率。这是一个使用叠加在条形图上的菱形数据集的示例,这可能是您正在寻找的。​​p>

    你可以看到一个例子,这个例子只有散点图和这个 sn-p ggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+geom_abline(intercept = 0, slope = 1 )

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 2022-01-22
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 2020-11-07
      • 2021-04-16
      相关资源
      最近更新 更多