三维密度图
library(ggplot2)
library(rayshader)
ggdiamonds = ggplot(diamonds) +
stat_density_2d(aes(x = x, y = depth, fill = stat(nlevel)),
geom = "polygon", n = 100, bins = 10, contour = TRUE) +
facet_wrap(clarity~.) +
scale_fill_viridis_c(option = "A")
par(mfrow = c(1, 2))
plot_gg(ggdiamonds, width = 5, height = 5, raytrace = FALSE, preview = TRUE)
plot_gg(ggdiamonds, width = 5, height = 5, multicore = TRUE, scale = 250,
zoom = 0.7, theta = 10, phi = 30, windowsize = c(800, 800))
render_snapshot(clear = TRUE)
facet_wrap分面显示;scale_fill_viridis_c为设置色盲友好色色带。plot_gg中raytrace是否添加光线追踪层,默认为FALSE;preview是否显示二维图像(俯视),默认为FALSE。multicore表示如果光线跟踪和“真”,将使用多种颜色来计算阴影矩阵,默认为FALSE(感觉开了没开没啥大区别啊)。scale为3dt图的高度。zoom、theta、phi为3d图视角参数。
三维地形图
library(rayshader)
library(reshape2)
library(ggplot2)
ggvolcano = volcano %>%
melt() %>%
ggplot() +
geom_tile(aes(x = Var1, y = Var2, fill = value)) +
geom_contour(aes(x = Var1, y = Var2, z = value), color = "black") +
scale_x_continuous("X", expand = c(0, 0)) +
scale_y_continuous("Y", expand = c(0, 0)) +
scale_fill_gradientn("Z", colours = terrain.colors(10)) +
coord_fixed()
par(mfrow = c(1, 2))
plot_gg(ggvolcano, width = 7, height = 4, raytrace = FALSE, preview = TRUE)
plot_gg(ggvolcano, multicore = TRUE, raytrace = TRUE, width = 7, height = 4,
scale = 300, windowsize = c(1400, 866), zoom = 0.6, phi = 30, theta = 30)
render_snapshot(clear = TRUE)
scale_x_continuous表示x轴从0开始,一点留白都没有。melt()数据变形函数。
三维柱状图
mtplot = ggplot(mtcars) +
geom_point(aes(x = mpg, y = disp, color = cyl)) +
scale_color_continuous(limits = c(0, 8))
par(mfrow = c(1, 2))
plot_gg(mtplot, width = 3.5, raytrace = FALSE, preview = TRUE)
plot_gg(mtplot, width = 3.5, multicore = TRUE, windowsize = c(800, 800),
zoom = 0.85, phi = 35, theta = 30, sunangle = 225, soliddepth = -100)
render_snapshot(clear = TRUE)
soliddepth为3d高度增加或减少的高度,应为这里数据是从100开始的,所以柱子高度减去100显示。
三维六边形密度图
library(rayshader)
library(ggplot2)
a = data.frame(x = rnorm(20000, 10, 1.9), y = rnorm(20000, 10, 1.2))
b = data.frame(x = rnorm(20000, 14.5, 1.9), y = rnorm(20000, 14.5, 1.9))
c = data.frame(x = rnorm(20000, 9.5, 1.9), y = rnorm(20000, 15.5, 1.9))
data = rbind(a, b, c)
#Lines
pp = ggplot(data, aes(x = x, y = y)) +
geom_hex(bins = 20, size = 0.5, color = "black") +
scale_fill_viridis_c(option = "C")
par(mfrow = c(1, 2))
plot_gg(pp, width = 5, height = 4, scale = 300, raytrace = FALSE, preview = TRUE)
plot_gg(pp, width = 5, height = 4, scale = 300, multicore = TRUE, windowsize = c(1000, 800))
render_camera(fov = 70, zoom = 0.5, theta = 130, phi = 35)
render_snapshot(clear = TRUE)
rbind函数为纵向追加,.cbind函数为横向增加函数。
渲染
par(mfrow = c(1, 1))
plot_gg(pp, width = 5, height = 4, scale = 300, multicore = TRUE, windowsize = c(1200, 960),
fov = 70, zoom = 0.4, theta = 330, phi = 40)
render_depth(focus = 0.68, focallength = 200)
fov为视角参数。focallength焦距,focus模糊深度0~1。