[英]Efficiently plotting hundreds of millions of points in R
plot()
是在 R 中繪制 1 億個左右數據點的最有效方法嗎? 我想繪制一堆這些Clifford Attractors 。 這是我從非常大的圖像縮小的示例:
這是我用來繪制非常大的 8K (7680x4320) 圖像的一些代碼的鏈接。
生成 50 或 1 億個點(使用 Rcpp)不需要很長時間,也不需要獲取顏色 + 透明度的十六進制值,但實際繪制和保存到磁盤的速度非常慢。
編輯:使用的代碼
# Load packages
library(Rcpp)
library(viridis)
# output parameters
output_width = 1920 * 4
output_height = 1080 * 4
N_points = 50e6
point_alpha = 0.05 #point transperancy
# Attractor parameters
params <- c(1.886,-2.357,-0.328, 0.918)
# C++ function to rapidly generate points
cliff_rcpp <- cppFunction(
"
NumericMatrix cliff(int nIter, double A, double B, double C, double D) {
NumericMatrix x(nIter, 2);
for (int i=1; i < nIter; ++i) {
x(i,0) = sin(A*x(i-1,1)) + C*cos(A*x(i-1,0));
x(i,1) = sin(B*x(i-1,0)) + D*cos(B*x(i-1,1));
}
return x;
}"
)
# Function for mapping a point to a colour
map2color <- function(x, pal, limits = NULL) {
if (is.null(limits))
limits = range(x)
pal[findInterval(x,
seq(limits[1], limits[2], length.out = length(pal) + 1),
all.inside = TRUE)]
}
# Obtain matrix of points
cliff_points <- cliff_rcpp(N_points, params[1], params[2], params[3], params[4])
# Calculate angle between successive points
cliff_angle <- atan2(
(cliff_points[, 1] - c(cliff_points[-1, 1], 0)),
(cliff_points[, 2] - c(cliff_points[-1, 2], 0))
)
# Obtain colours for points
available_cols <-
viridis(
1024,
alpha = point_alpha,
begin = 0,
end = 1,
direction = 1
)
cliff_cols <- map2color(
cliff_angle,
c(available_cols, rev(available_cols))
)
# Output image directly to disk
jpeg(
"clifford_attractor.jpg",
width = output_width,
height = output_height,
pointsize = 1,
bg = "black",
quality = 100
)
plot(
cliff_points[-1, ],
bg = "black",
pch = ".",
col = cliff_cols
)
dev.off()
我最近發現了 R 的Scattermore包,它比 R 的標准繪圖函數快一個數量級。 scattermoreplot()
需要大約 2 分鍾來繪制具有顏色和透明度的 100m 點,而plot()
需要大約半小時。
我目前正在探索datashader ( http://www.datashader.org )。 如果你願意使用 python,這可能是一個優雅的問題解決方案。
也許來自 ggplo2 包的 geom_hex() 可以是一個解決方案? https://ggplot2.tidyverse.org/reference/geom_hex.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.