[英]Is there a way to use R to break chart axis and break linear regression line?
我試圖弄清楚如何修改一個散點圖,該散點圖包含沿由大間隙分隔的連續體的兩組數據。 該圖需要在 x 軸和回歸線上中斷。
這段使用 ggplot2 庫的 R 代碼准確地呈現了數據,但由於圖形上有大量空白空間而難看。 皮爾遜相關系數為 -0.1380438。
library(ggplot2)
p <- ggplot(, aes(x = dis, y = result[, 1])) + geom_point(shape = 1) +
xlab("X-axis") +
ylab("Y-axis") + geom_smooth(color = "red", method = "lm", se = F) + theme_classic()
p + theme(plot.title = element_text(hjust = 0.5, size = 14))
此 R 代碼使用 gap.plot 來生成所需的中斷,但回歸線不包含中斷並且不能正確反映斜率。 正如您所看到的,回歸線的斜率不像上圖那樣尖銳,並且這些不同組之間的線的斜率需要有明顯的區別。
library(plotrix)
gap.plot(
x = dis,
y = result[, 1],
gap = c(700, 4700),
gap.axis = "x",
xlab = "X-Axis",
ylab = "Y-Axis",
xtics = seq(0, 5575, by = 200)
)
abline(v = seq(700, 733) , col = "white")
abline(lm(result[, 1] ~ dis), col = "red", lwd = 2)
axis.break(1, 716, style = "slash")
使用MS畫圖,我創建的圖形應該是什么樣子的近似值。 請注意頂部的斷點以及兩組之間回歸線上的不連續性。
一種解決方案是將回歸線分成兩部分繪制,使用ablineclip
限制每次繪制的內容。 (類似於@tung 的建議,盡管很明顯您想要單個圖形的外觀而不是小平面的外觀。)這是如何工作的:
library(plotrix)
# Simulate some data that looks roughly like the original graph.
dis = c(rnorm(100, 300, 50), rnorm(100, 5000, 100))
result = c(rnorm(100, 0.6, 0.1), rnorm(100, 0.5, 0.1))
# Store the location of the gap so we can refer to it later.
x.axis.gap = c(700, 4700)
# gap.plot() works internally by shifting the location of the points to be
# plotted based on the gap size/location, and then adjusting the axis labels
# accordingly. We'll re-compute the second half of the regression line in the
# same way; these are the new values for the x-axis.
dis.alt = dis - x.axis.gap[1]
# Plot (same as before).
gap.plot(
x = dis,
y = result,
gap = x.axis.gap,
gap.axis = "x",
xlab = "X-Axis",
ylab = "Y-Axis",
xtics = seq(0, 5575, by = 200)
)
abline(v = seq(700, 733), col = "white")
axis.break(1, 716, style = "slash")
# Add regression line in two pieces: from 0 to the start of the gap, and from
# the end of the gap to infinity.
ablineclip(lm(result ~ dis), col = "red", lwd = 2, x2 = x.axis.gap[1])
ablineclip(lm(result ~ dis.alt), col = "red", lwd = 2, x1 = x.axis.gap[1] + 33)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.