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
版本:当然,通常可以通过不绘制原始数据来避免该问题
最佳答案
感谢 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
图层为栅格,其他所有内容为矢量图形。总体而言,该图看起来与问题中的图相同,但放大显示差异:将此与全光栅图形进行比较:
关于r - 如何光栅化ggplot的单层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47222764/