令人窒息的3D作图,从2D轻松转换。
2019-07-11 本文已影响40人
9d760c7ce737
有一天我在逛Twitter的时候,看到了这样一幅图:

我觉得很炫酷,开心的是这个图是用R语言画的,更开心的是这个图可以用ggplot2对象轻松转换。
这个R包叫rayshader
, 一开始的作用是专门给地图加上水流,给山川加上阴影

有比较详细的教程
https://github.com/tylermorganwall/rayshader
https://www.tylermw.com/3d-ggplots-with-rayshader/
而我在意的是,如何快速地把ggplot2画出来的图变成3D的。就像这样

首先我们来安装R包
devtools::install_github("tylermorganwall/rayshader")
这个包中的核心函数是plot_gg
,他可以把任意一个ggplot2对象渲染成3D图片
比如,我们可以轻易地用ggplot2
画一张图
library(ggplot2)
ggplot(mtcars) +
geom_point(aes(x = mpg, y = disp, color = cyl)) +
scale_color_continuous(limits = c(0, 8))

现在我们只要把这个图保存为ggplot2对象
mtplot = ggplot(mtcars) +
geom_point(aes(x = mpg, y = disp, color = cyl)) +
scale_color_continuous(limits = c(0, 8))
然后用plot_gg
就可以无痛转换
library(rayshader)
plot_gg(mtplot, width = 3.5, multicore = TRUE, windowsize = c(800, 800),
zoom = 0.85, phi = 35, theta = 30, sunangle = 225, soliddepth = -100)
这个过程需要一点时间,完成后会弹出一个可以交互的窗口,图就画完成了

下面切换到自己的数据上,在果子学生信公众号回复“果子学生信”可以获得这个课前热身的数据。
他以最简单的方式表明,R语言的作图很简单:
1.第一行的数据
2.第二行加载画图的R包
3.第三行运行画图的函数
load(file = "EGG_20190106.Rda")
library(clusterProfiler)
dotplot(EGG)

现在我们把这个图变成3D图,首先要把这个图保存为一个ggplot2对象
gg <- dotplot(EGG)
那么现在理论上就是运行一下plot_gg
就行了
library(rayshader)
plot_gg(gg,width = 6.8,height = 6.8, multicore = TRUE,
zoom = 0.85, phi = 35, theta = 30, sunangle = 225, soliddepth = -100)
渲染需要时间,小电脑需要谨慎。

我觉得这些图出除了汇报的时候有点用,暂时想不出来有什么大用。
如果加一个preview
参数,可以导出为静态图片
plot_gg(gg,width = 6.8,height = 6.8,preview = TRUE)

放入PPT中,可以作为立体背景使用。

这个包的功能还有很多,有兴趣的根据提供的那两个教程继续把玩。