在散點圖中,我想沿著描述 x 和 y 之間關系的方程顯示相關系數。我已經創建了我的資料材料,這是我目前的代碼:
library(tidyverse)
# Creation of datamaterial
salary <- c(95, 100, 105, 110, 120, 124, 135, 150, 165, 175, 225, 230, 235, 260)
height <- c(160, 150, 182, 165, 172, 175, 183, 187, 174, 193, 201, 172, 180, 188)
fakenumbers <- data.frame(salary, height)
cor(height, salary, method = c("pearson"))
# Creation of scatterplot
r <- ggplot(fakenumbers, aes(x = height, y = salary))
geom_point(size = 3, shape = 21, color = "black", fill = "blue")
labs(y = "Hourly salary
(sek)", x = "height (cm)", title = "Relationship between height and salary (made up data)")
theme_classic() theme(plot.title = element_text(hjust = 0.5, size = 18),
axis.title = element_text(size = 15),
axis.title.y = element_text(angle = 0, vjust = 0.5),
axis.text = element_text(size = 11))
# Adding a regressionline
r geom_smooth(method = lm, formula = y ~ x, se = FALSE)
在坐標系內部,在回歸線旁邊,我想要顯示“r = 0.588”和一些描述線性關系的方程。我怎樣才能做到這一點,最好使用 ggplot() 或其他一些函式?
uj5u.com熱心網友回復:
我們可以用ggpubrpackage來做,添加stat_cor(p.accuracy = 0.001, r.accuracy = 0.01)到你的代碼中:
library(ggpubr)
library(tidyverse)
r <- ggplot(fakenumbers, aes(x = height, y = salary))
geom_point(size = 3, shape = 21, color = "black", fill = "blue")
stat_cor(p.accuracy = 0.001, r.accuracy = 0.01)
labs(y = "Hourly salary
(sek)", x = "height (cm)", title = "Relationship between height and salary (made up data)")
theme_classic() theme(plot.title = element_text(hjust = 0.5, size = 18),
axis.title = element_text(size = 15),
axis.title.y = element_text(angle = 0, vjust = 0.5),
axis.text = element_text(size = 11))

uj5u.com熱心網友回復:
這是一個基本的R方式。定義一個公式fo,計算回歸,并定義一個eqation。
corr <- cor(height, salary, method = c("pearson"))
fo <- salary ~ height
fit <- lm(fo, fakenumbers)
(eq <- paste0(all.vars(fo)[1], ' ~ ', paste0(round(coef(fit), 2),
gsub('\\*\\(Intercept\\)', '',
paste0('*', names(coef(fit)))), collapse=' ')))
# [1] "salary ~ -281.58 salary ~ 2.49*height"
然后使用變數plot(),abline()和text()。
plot(fo, fakenumbers, pch=20, col=4,
xlab='height (cm)', ylab='Hourly salar (sec)',
main='Relationship between height and salary (made up data)')
abline(fit, col=4)
text(149, 250, bquote(italic('r=')~.(round(corr, 3))), adj=0, cex=.8)
text(149, 235, eq, adj=0, cex=.8)

資料:
fakenumbers <- structure(list(salary = c(95, 100, 105, 110, 120, 124, 135, 150,
165, 175, 225, 230, 235, 260), height = c(160, 150, 182, 165,
172, 175, 183, 187, 174, 193, 201, 172, 180, 188)), class = "data.frame", row.names = c(NA,
-14L))
uj5u.com熱心網友回復:
其他方式:
round(cor(height, salary, method = c("pearson")), 4) -> corr
然后geom_text用于顯示相關系數:
r
geom_smooth(method = lm, formula = y ~ x, se = FALSE)
geom_text(x = 152, y = 250,
label = paste0('r = ', corr),
color = 'red')

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400195.html
上一篇:geom_boxplot:用第二個矩形替換IQR和胡須之間的線
下一篇:縮短if陳述句Python
