【问题标题】:ggplot2: Make geom_abline() draw independent slopes and intercepts for each plot of the facet_wrap()ggplot2:让 geom_abline() 为 facet_wrap() 的每个图绘制独立的斜率和截距
【发布时间】:2020-09-18 00:52:16
【问题描述】:

使用geom_abline(),我想知道我是否可以实现 3 种类型的 face_warpped 图:

首先,每个图的截距为 12,但从左上角到右下角的斜率从 1 到 9,

其次,每个地块的斜率为 3,但从左上角到右下角的斜率从 3 开始到 12,

第三,每个图都有不同的截距(从 3 到 12),以及从 1 到 9 的不同斜率。

这是我尝试但没有成功的方法:

library(ggplot2)

hsb <- read_csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')
nine <- subset(hsb, sch.id %in% unique(sch.id)[1:9])

## First (each plot has an intercept of 12, but slope from topleft to bottom-right start from 1 to 9):
ggplot(nine) + aes(ses, math)+ geom_point(size=1) +
  facet_wrap(~sch.id)+geom_abline(intercept = 12,slope = 1:9, col="blue")

## Second (each plot has an slope of 3, but slope from topleft to bottom-right start from 3 to 12):
ggplot(nine) + aes(ses, math)+ geom_point(size=1) +
  facet_wrap(~sch.id)+geom_abline(intercept = 3:12,slope = 3, col="blue")

## Third (each plot has a different intercept (from 3 to 12), and different slope from 1 to 9):
ggplot(nine) + aes(ses, math)+ geom_point(size=1) +
  facet_wrap(~sch.id)+geom_abline(intercept = 3:12,slope = 1:9, col="blue")

【问题讨论】:

    标签: r ggplot2 plot


    【解决方案1】:

    ggplot 中的其他所有内容一样,您希望为 ablines 提供一个数据框,并使用 aes 映射截距和斜率:

    library(ggplot2)
    
    hsb <-
      read_csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')
    nine <- subset(hsb, sch.id %in% unique(sch.id)[1:9])
    
    slopes_df <- data.frame("sch.id" = unique(nine$sch.id),
                            "interc" = 12,
                            "slopes" = 1:9)
    
    ## First (each plot has an intercept of 12, but slope from topleft to bottom-right start from 1 to 9):
    ggplot(nine) + aes(ses, math) + geom_point(size = 1) +
      facet_wrap( ~ sch.id) + 
      geom_abline(data = slopes_df, aes(intercept = interc, slope = slopes), col = "blue")
    

    将制作此图表:

    【讨论】:

      猜你喜欢
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 2020-03-25
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多