如何栅格化ggplot的单层? [英] How to rasterize a single layer of a ggplot?
问题描述
Matplotlib可以栅格化绘图的各个元素,并将其保存为混合像素/矢量图形(.pdf
)(请参见例如这个答案). 如何在R
和ggplot2
中实现相同的功能?
Matplotlib allows to rasterize individual elements of a plot and save it as a mixed pixel/vector graphic (.pdf
) (see e.g. this answer). How can the same achieved in R
with ggplot2
?
以下是一个玩具问题,在此我仅想光栅化geom_point
层.
The following is a toy problem in which I would like to rasterize only the geom_point
layer.
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需要大约1s来渲染图形.在下面您可以看到.png
版本:
When saved as .pdf
as is, Adobe reader DC needs ~1s to render the figure. Below you can see a .png
version:
当然,通常可以通过不绘制原始数据来避免此问题
Of course, it is often possible to avoid the problem by not plotting raw data
推荐答案
感谢Viktor的 ggrastr
软件包佩图霍夫& Evan Biederstedt ,现在可以栅格化各个图层.但是,当前(2018-08-13)仅支持geom_point和geom_tile.和 Teun van den Brand的作品,现在可以通过将其包装在ggrastr::rasterise()
中来对任何单独的ggplot图层进行栅格化:
Thanks to the ggrastr
package by Viktor Petukhov & Evan Biederstedt, it is now possible to rasterize individual layers. However, currently (2018-08-13), only geom_point and geom_tile are supported. and work by Teun van den Brand it is now possible to rasterize any individual ggplot layer by wrapping it in ggrastr::rasterise()
:
# 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
.
Previously, only a few geoms were supported:
To use it, you had to replace geom_point
by 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
图层作为栅格,而其他所有内容作为矢量图形.总体而言,该数字看起来像是问题中的那个,但放大可以看到不同之处:
将此与所有栅格图形进行比较:
This yields a pdf
that contains only the geom_point
layer as raster and everything else as vector graphic. Overall the figure looks as the one in the question, but zooming in reveals the difference:
Compare this to an all-raster graphic:
这篇关于如何栅格化ggplot的单层?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!