r - 如何根据数据属性的平均值在 xyplot 中添加一条线?
问题描述
我已经创建了我想要得到的基础图,我只是不知道如何根据 USArrests 数据集中谋杀属性的平均值在图中添加一条线。之后,我还需要根据州名是高于还是低于线来为它们着色。
我需要的图表: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)
}
解决方案
您的图表似乎显示了一条倾斜的回归线,而不是平均值的水平线。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])
}
)
推荐阅读
- python - 'function' 对象没有属性 'today'
- python - Python 将 json 插入 Postgres
- vba - 如何使用电子邮件中的主题行将附件分类到本地文件夹中?
- json - Spark 应用程序从 JSON 文件中读取动态 JSON 字段的值
- reactjs - CustomEvents 和 React.js 组件
- angular - 自定义验证器不会改变我的 ngClass
- java - 如何使用 System.out.println 找到 Java 类?
- java - 是什么导致码头空闲超时
- matlab - 使用 Scilab 绘制瀑布图
- java - 在使用 Java 流进行排序时将数字解析为字符串的简单方法?