你如何强制Rmarkdown图是Square而不是Rectangle?

时间:2018-04-29 04:42:32

标签: r

我有一个广义线性模型(GLM),我正在绘制诊断信息,以便在MASS包中使用glm.diag.plots函数。但它倾向于绘制矩形而不是方形,这对于出版来说非常难看。

下面是一些示例代码,用于显示.Rmd文件中的问题。在Rstudio中,您可以直接拖动窗口直到它的方形,但在Rmarkdown文档中不可能,并且我想手动强制执行方形。 enter image description here

我在ggplot文档中查看了强制执行方形绘图的方法,但找不到任何内容。 glm.diag.plot()似乎使用split.screen(),它也没有提供强制宽高比的任何文档。

2 个答案:

答案 0 :(得分:3)

您似乎正在使用包glm.diag.plots中的boot来获取图表。 如果您愿意,可以使用ggplot重新创建它们。这是一个例子:

某些型号:

data(anorexia, package = "MASS")

anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
                family = gaussian, data = anorexia)

glm.diag.plots输出

library(boot)
glm.diag.plots(anorex.1)

enter image description here

要在ggplot中创建每个地块,请先从glm.diag.plots

获取一个对象
z <- glm.diag.plots(anorex.1, ret = T)

然后绘制每个情节:

library(ggplot2)

plot1 <- ggplot(data.frame(x = predict(anorex.1),
                           y = z$res))+
  geom_point(aes(x, y)) +
  xlab("Linear predictor") +
  ylab("Residuals") +
  theme_bw()+
  theme(aspect.ratio=1)

plot2 <- ggplot(data.frame(x = qnorm(ppoints(length(z$rd)))[rank(z$rd)],
                           y = z$rd)) +
  geom_point(aes(x, y)) +
  xlab("Ordered deviance residuals") +
  ylab("Quantiles of standard normal") +
  geom_abline(intercept = 0, slope = 1, lty =2) +
  theme_bw()+
  theme(aspect.ratio=1)

plot3 <- ggplot(data.frame(x = z$h/(1-z$h),
                           y = z$cook)) +
  geom_point(aes(x, y)) +
  xlab("h/(h-1)") +
  ylab("Cook statistic") +
  theme_bw()+
  theme(aspect.ratio=1)

plot4 <- ggplot(data.frame(x = 1:length(z$cook),
                           y = z$cook)) +
  geom_point(aes(x, y)) +
  xlab("Case") +
  ylab("Cook statistic") +
  theme_bw()+
  theme(aspect.ratio=1)

然后合并它们

library(cowplot)

plot_grid(plot1, plot2, plot3, plot4, ncol = 2)

enter image description here

现在您可以按照自己的方式自定义每个地图。

答案 1 :(得分:1)

@ rawr的评论是正确的;这是一个knitr / markdown问题,而不是glm.diag或ggplot或其他任何问题。您需要做的就是使用fig.widthfig.height指定所需的输出高度和宽度(默认为英寸)。

enter image description here