r - 如何更改“pairs”函数生成的散点图对角线上的文本?
问题描述
我想更改 R 中以下代码生成的对角线上的文本(我想更改显示 Sepal.Length、Sepal.Width、Petal.Length 和 Petal.Width 的文本)。
我尝试在“pairs”函数中为 diag.panel 参数插入一些东西,但没有运气。
#Extracts the iris species column from the iris dataset
iris_class = iris$Species
#Change the class from characters to numerical values for indexing
# #1 = Iris-setosa
# #2 = Iris-versicolor
# #3 = Iris-virginica
class_to_number = as.numeric(factor(iris_class))
#A function to show the linear regression line in each graph
upper_panel_regression_line = function(x,y, ...){
points(x,y,...)
linear_regression = lm(y~x)
linear_regression_line = abline(linear_regression)
}
#A function to calculate and show the R-squared value of each panel
lower_panel_r_squared = function(x, y, ...){
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 2, 0, 2))
r = cor(x, y)
r_squared = round(r^2, digits = 2)
text_of_r_squared = paste0("R-squared = ", r_squared)
text(1, 1, text_of_r_squared)
}
pairs(iris[1:4], main = "Predicting Iris Class",
lower.panel=lower_panel_r_squared, upper.panel =
upper_panel_regression_line, col=c("red","blue","green") [class_to_number])
解决方案
diag_custom_labels <- function(x, y, labels, cex, font, ...) {
if (!exists('i')) i <<- 1
text(mean(x), mean(y), c('my', 'custom', 'diag', 'labels')[[i]], cex = cex)
i <<- i + 1
}
pairs(iris[1:4], main = "Predicting Iris Class",
lower.panel=lower_panel_r_squared, upper.panel = upper_panel_regression_line,
text.panel = diag_custom_labels,
col=c("red","blue","green") [class_to_number])
推荐阅读
- python - 为什么具有假定形状参数的子程序不能具有内部功能?
- flutter - 在提供程序中使用流与颤动
- minio - “mc cp --recursive”和“mc mirror --overwrite”有什么不同
- tensorflow - 大于 2GB 的张量流图
- angular - 离子保持登录
- html - HTML 到 PDF - 以英寸为单位的元素尺寸与预期不符
- javascript - 如何使用数据表计算两个时间之间的持续时间?
- python - 当它位于 /usr/local/bin/python3.6 时,如何在 ubuntu 上卸载 python3.6
- android - 如何使用从 url 下载的 apk 文件自动更新应用程序?
- javascript - 在 querySelectorAll() 之前调用 querySelector()