bee*_*oot 13 r ggplot2 ggfortify
使用autoplotfrom ggfortify来创建诊断图:
library(ggplot2)
library(ggfortify)
mod <- lm(Petal.Width ~ Petal.Length, data = iris)
autoplot(mod, label.size = 3)
Run Code Online (Sandbox Code Playgroud)
是否可以更改轴和标题(轻松)?我想翻译它们.
该函数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)
Run Code Online (Sandbox Code Playgroud)
这里我只修改了轴标签,但你可以单独更改关于图的任何内容(主题,颜色,标题,大小).
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")
Run Code Online (Sandbox Code Playgroud)
请不要忘记让我们知道是否有帮助:)
@ 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)
Run Code Online (Sandbox Code Playgroud)