r - 如何光栅化ggplot的单层?

标签 r ggplot2

Matplotlib 允许栅格化绘图的单个元素并将其保存为混合像素/矢量图形( .pdf )(参见例如 this answer )。如何在 R 中实现相同的功能与 ggplot2 ?

以下是一个玩具问题,我只想光栅化 geom_point层。

set.seed(1)
x <- rlnorm(10000,4)
y <- 1+rpois(length(x),lambda=x/10+1/x)
z <- sample(letters[1:2],length(x), replace=TRUE)

p <- ggplot(data.frame(x,y,z),aes(x=x,y=y)) +
  facet_wrap("z") +
  geom_point(size=0.1,alpha=0.1) +
  scale_x_log10()+scale_y_log10() +
  geom_smooth(method="gam",formula = y ~ s(x, bs = "cs"))
print(p)
ggsave("out.pdf", p)
当另存为 .pdf照原样,Adobe reader DC 需要大约 1 秒来渲染图形。下面你可以看到一个 .png版本:
out.png
当然,通常可以通过不绘制原始数据来避免该问题

最佳答案

感谢 ggrastr package by Viktor Petukhov & Evan Biederstedt ,现在可以栅格化单个图层。但是,目前(2018-08-13)仅支持 geom_point 和 geom_tile。和 work by Teun van den Brand现在可以通过将其包裹在 ggrastr::rasterise() 中来栅格化任何单个 ggplot 图层。 :

# install.packages('devtools')
# remotes::install_github('VPetukhov/ggrastr')

df %>% ggplot(aes(x=x, y=y)) +
      # this layer will be rasterized:
      ggrastr::rasterise(geom_point(size=0.1, alpha=0.1)) +
      # this one will still be "vector":
      geom_smooth()
以前,仅支持少数几何体:
要使用它,您必须替换 geom_point来自 ggrastr::geom_point_rast .
例如:
# install.packages('devtools')
# devtools::install_github('VPetukhov/ggrastr')
library(ggplot2)

set.seed(1)
x <- rlnorm(10000, 4)
y <- 1+rpois(length(x), lambda = x/10+1/x)
z <- sample(letters[1:2], length(x), replace = TRUE)

ggplot(data.frame(x, y, z), aes(x=x, y=y)) +
  facet_wrap("z") +
  ggrastr::geom_point_rast(size=0.1, alpha=0.1) +
  scale_x_log10() + scale_y_log10() +
  geom_smooth(method="gam", formula = y ~ s(x, bs = "cs"))
ggsave("out.pdf")
这会产生 pdf仅包含 geom_point图层为栅格,其他所有内容为矢量图形。总体而言,该图看起来与问题中的图相同,但放大显示差异:
zoom-in view of example picture
将此与全光栅图形进行比较:
all-raster for comparison

关于r - 如何光栅化ggplot的单层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47222764/

相关文章:

r - ggplot 中使用facet_grid 进行绘图的方法

r - **ggplot2** : Difference between scale_x_continuous(breaks = ) and xlim() (or eqivalently scale_y_continouous(breaks=) and ylim)

r - 为生存图指定自定义时间点

r - 使用 ggplot2 绘制组的时间序列图

R 并行处理错误 `Error in checkForRemoteErrors(val) : 6 nodes produced errors; first error: subscript out of bounds`

r - 内存中没有变量名的数据仍然是 R 中的对象吗?

R Leaflet 离线 map 图 block 未加载

r - ggplot2 错误 - 替换有 100 行,数据有 2

r - 在 R 中绘制没有零值的直方图

r - 在绘图 R 中省略坐标轴