首页 > 解决方案 > 如何根据数据属性的平均值在 xyplot 中添加一条线?

问题描述

我已经创建了我想要得到的基础图,我只是不知道如何根据 USArrests 数据集中谋杀属性的平均值在图中添加一条线。之后,我还需要根据州名是高于还是低于线来为它们着色。

我的图表:https ://ibb.co/V3VkYt4

我需要的图表:https ://ibb.co/4TTnQM1

我尝试添加一个带有 Murder 属性的 abline 作为输入,并且该线出现在我的图表之外,不确定我做错了什么。

library(lattice)
textPlot <- function()
{
  data <- cbind(rownames(USArrests), USArrests)
  names(data) <- c("State", names(data)[2:5])

averageM <- mean(USArrests$Murder)

         xyplot(Murder~UrbanPop, data, 
         groups=State, panel=drawText, 
         main="Murder vs. Urban Population")

}

drawText <- function(x,y,groups,...)
  {
    panel.text(x=x,y=y,label=groups,cex=y/10)
}   

标签: rlattice

解决方案


您的图表似乎显示了一条倾斜的回归线,而不是平均值的水平线。Lattice 可以xyplot直接从带有 的变量panel.lmline或带有 的回归模型(或常数)中添加回归线panel.abline。需要做更多的工作来对高于或低于选定谋杀率的州进行分类。这是用格子显示两种类型的回归线的一种方法。

# Load the lattice package, create data.frame with state names from USAarrests
  library(lattice)
  df <- data.frame(State = rownames(USArrests), USArrests)

# Determine regression and mean murder rate outside of xyplot()
# However, these operations don't have to be done outside of the lattice function
  fm <- lm(Murder ~ UrbanPop, df)
  averageM <- mean(USArrests$Murder)

# Add a variable to the data.frame indicating the classification
  df$type <- factor(ifelse(df$Murder < fm$fitted, "low", "high"))

# Plot via lattice with explicit panel() function
  xyplot(Murder ~ UrbanPop, data = df,
    panel = function(x, y, ...) {
      panel.abline(fm, col = "red", lwd = 2)
#     panel.lmline(x, y, col = "red", lwd = 2) # This would do the same
      panel.abline(h = averageM, col = "red", lty = 2, lwd = 2)
#     panel.abline(h = mean(y), col = "red", lty = 2, lwd = 2) # This would do the same
      panel.text(x, y, labels = df$State, cex = y/10, col = c(2,4)[df$type])
    }
  )

推荐阅读