繁体   English   中英

ggplot2:使 geom_abline() 为 facet_wrap() 的每个图绘制独立的斜率和截距

[英]ggplot2: Make geom_abline() draw independent slopes and intercepts for each plot of the facet_wrap()

使用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")

ggplot所有其他内容一样,您希望为ggplot提供一个数据框,并使用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")

将制作此图: 在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM