首页 > 解决方案 > 如何更改“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])

标签: rplot

解决方案


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])

在此处输入图像描述


推荐阅读