使用autoplot
fromggfortify
创建诊断图:
library(ggplot2)
library(ggfortify)
mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod, label.size = 3)
是否可以(轻松)更改轴和绘图标题?我想翻译它们。
该函数autoplot.lm
返回一个 S4 对象(ggmultiplot 类,请参阅 参考资料?`ggmultiplot-class`
)。如果您查看帮助文件,您会发现它们具有用于各个图的替换方法。这意味着您可以提取单个图,对其进行修改,然后将其放回原处。例如:
library(ggplot2)
library(ggfortify)
mod <- lm(Petal.Width ~ Petal.Length, data = iris)
g <- autoplot(mod, label.size = 3) # store the ggmultiplot object
# new x and y labels
xLabs <- yLabs <- c("a", "b", "c", "d")
# loop over all plots and modify each individually
for (i in 1:4)
g[i] <- g[i] + xlab(xLabs[i]) + ylab(yLabs[i])
# display the new plot
print(g)
在这里,我只修改了轴标签,但您可以单独更改有关图的任何内容(主题、颜色、标题、大小)。
@user20650 提出的解决方案既有趣又优雅。
这是一个不太优雅的解决方案myautoplot
,它基于autoplot
. 我希望它可以帮助你。在此处
下载该myautoplot
功能并将其保存在您的工作目录中,名称为.
然后,使用以下代码:myautoplot.r
library(ggplot2)
library(ggfortify)
source("myautoplot.r")
mod <- lm(Petal.Width ~ Petal.Length, data = iris)
####
# Define x-labels, y-labels and titles
####
# Residuals vs Fitted Plot
xlab_resfit <- "Xlab ResFit"
ylab_resfit <- "Ylab ResFit"
title_resfit <- "Title ResFit"
# Normal Q-Q Plot
xlab_qqplot <- "Xlab QQ"
ylab_qqplot <- "Ylab QQ"
title_qqplot <- "Title QQ"
# Scale-Location Plot
xlab_scaleloc <- "Xlab S-L"
ylab_scaleloc <- "Ylab S-L"
title_scaleloc <- "Title S-L"
# Cook's distance Plot
xlab_cook <- "Xlab Cook"
ylab_cook <- "Ylab Cook"
title_cook <- "Title Cook"
# Residuals vs Leverage Plot
xlab_reslev <- "Xlab Res-Lev"
ylab_reslev <- "Ylab Res-Lev"
title_reslev <- "Title Res-Lev"
# Cook's dist vs Leverage Plot
xlab_cooklev <- "Xlab Cook-Lev"
ylab_cooklev <- "Ylab Cook-Lev"
title_cooklev <- "Title Cook-Lev"
# Collect axis labels and titles in 3 lists
xlab_list <- list(resfit=xlab_resfit, qqplot=xlab_qqplot,
scaleloc=xlab_scaleloc, cook=xlab_cook, reslev=xlab_reslev,
cooklev=xlab_cooklev)
ylab_list <- list(resfit=ylab_resfit, qqplot=ylab_qqplot,
scaleloc=ylab_scaleloc, cook=ylab_cook, reslev=ylab_reslev,
cooklev=ylab_cooklev)
title_list <- list(resfit=title_resfit, qqplot=title_qqplot,
scaleloc=title_scaleloc, cook=title_cook, reslev=title_reslev,
cooklev=title_cooklev)
# Pass the lists of axis labels and title to myautoplot
myautoplot(mod, which=1:6, xlab=xlab_list,
ylab=ylab_list,
title=title_list)
library(ggplot2)
library(ggfortify)
mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod,which=c(1:6), ncols=2) #total 6 plots in two columns
#change axes label & title of plot 1. similarly by changing 'which' parameters count you can label other plots.
autoplot(mod,which=1) +
labs(x="x-axis label of fig1", y="y-axis label of fig1", title="Fig1 plot")
请不要忘记让我们知道它是否有帮助:)