在ggplot2中去除边框

3

我想在使用ggplot2输出的.png文件中去掉白边。我正在Windows 10上使用Rstudio,ggplot2geom_raster。在论坛上搜索并尝试了一些参数后,我最终得出了这个代码(仍然不起作用):

library(ggplot2)
library(datasets)

png(file = "Out.png")

par(mar=rep(0, 4), plt=c(0.1,0.9,0.1,0.9), xpd=NA)

ggplot(faithfuld, aes(waiting, eruptions)) +
geom_raster(aes(fill = density))+
theme(axis.line        = element_blank(),
      axis.text        = element_blank(),
      axis.ticks       = element_blank(),
      axis.title       = element_blank(),
      panel.background = element_blank(),
      panel.border     = element_blank(),
      panel.margin = unit(0,"null"),
      legend.position = "none",
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      plot.background  = element_blank(),
      plot.margin = rep(unit(0,"null"),4))

dev.off()

这段代码生成以下png图片:

enter image description here


这里有一些答案:如何去除 ggplot 绘图区域周围的边距 - Sandy Muspratt
感谢您提供的不同类似案例链接。经过一些尝试,似乎只有Floo提供的使用cowplot包的链接在这种情况下有效(可能是因为geom_raster或包版本)。 - Maurice clere
看起来你在两个轴上都缺少了 scale_*_*(expand = c(0, 0))axis.ticks.length = unit(0, "mm"))。这在给定的链接中提到,但不完全是标记为重复的那个问题。 - aosmith
1个回答

3
即使有点hacky,你仍然可以使用cowplot软件包来实现这个目标,方法如下:
library(ggplot2)
library(datasets)
require(cowplot)
base <- ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density)) +
  theme_nothing() + labs(x = NULL, y = NULL) 
plot_grid(base, scale=1.1)

- theme_nothing() + labs(x = NULL, y = NULL)是使用theme(...)的简便方式。 - plot_grid(..., scale=1.1)是重要部分,它将绘图缩放以覆盖白色边框。
这样就得到了以下结果:

enter image description here


嗨Floo,是的,它有效。你是怎么想到1.1的?只是补充一下信息:如果我们不使用图例,它也可以工作。但这已经足够好了!非常感谢。 - Maurice clere

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接