使用autoplot
中的ggfortify
创建诊断图:
library(ggplot2)
library(ggfortify)
mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod, label.size = 3)
是否可以更改轴和标题(轻松)?我想翻译它们。
答案 0 :(得分:6)
函数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)
这里我只修改了轴标签,但你可以单独更改关于图的任何内容(主题,颜色,标题,尺寸)。
答案 1 :(得分:5)
@ user20650提出的解决方案既有趣又优雅。
这是一个不太优雅的解决方案,基于myautoplot
,autoplot
的修改版本。我希望它可以帮助你。
下载myautoplot
功能here并将其保存在名为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)
答案 2 :(得分:4)
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")
请不要忘记告诉我们是否有帮助:)