一个震撼的交互型3D可视化R包 - rayshader作者:张虎 协和 编辑:陈同 生信宝典 
虽然3D 的plot见得比较多了,但是看见这样的R包 ,我的心还是砰了一下,这个简直不能再好看了! 关键是!!!敲黑板,这个R 包超简单!!!对于刚学习R语言的同学们来说,会被圈粉哒! 该包的主要功能就是将ggplot2画出来的2D 图像变为3D 图像,不说废话,直接上代码。 # 安装rayshader包 install.packages('remote') remotes::install_github('tylermorganwall/rayshader') library(rayshader) library(ggplot2)
# 查看数据格式 head(diamonds)
# 绘制二维密度图 gg = ggplot(diamonds, aes(x, depth)) + stat_density_2d(aes(fill = stat(nlevel)), #绘制密度等高线图 geom = 'polygon', n = 100,bins = 10, contour = TRUE) + facet_wrap(clarity~.) + # 按clarity分类 scale_fill_viridis_c(option = 'A') # 将map颜色设置为“岩浆”色,简称为“A”,共有“A”,“B”,“C”,“D”和“E”五种;gg # 绘制2D图
# 转成3D图,只需要plot_gg函数即可 plot_gg(gg,multicore=TRUE,width=5,height=5,scale=250)

打开后,可以像任何其他光线图一样操作绘图 - 可以调用render_camera() 以编程方式更改摄像机位置,render_snapshot() 可以保存或输出当前视图,甚至可以使用render_depth() 来渲染光滑深度场效应。还可以更改甚至删除光源,并将任何参数传递给plot_gg() ,绘制为plot_3d() 。 # 如果缺失sf包,建议先安装 library(sf)
nc = st_read(system.file('shape/nc.shp', package='sf'), quiet = TRUE) #加载包自带的数据 gg_nc = ggplot(nc) + # 加载North Carolina地图 geom_sf(aes(fill = AREA)) + # 绘制地理数据模型,sf对象,全称Simple feature scale_fill_viridis('Area') + # 按区域上色 ggtitle('Area of counties in North Carolina') + # 绘制题目 theme_bw()
plot_gg(gg_nc, multicore = TRUE, width = 6 ,height=2.7, fov = 70) #加载图形 render_depth(focallength=100,focus=0.72)

# 随机取三组数字,并且对其进行合并,两列,一列X,一列Y 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) class(data) #其实如果我们有相同类型的数据,也可以仿照该组织方式进行合并;# Lines pp = ggplot(data, aes(x=x, y=y)) + geom_hex(bins = 20, size = 0.5, color = 'black') + # 绘制六边形图 scale_fill_viridis_c(option = 'C') plot_gg(pp, width = 4, height = 4, scale = 300, multicore = TRUE)
# No lines pp_nolines = ggplot(data, aes(x=x, y=y)) + geom_hex(bins = 20, size = 0) + scale_fill_viridis_c(option = 'C') plot_gg(pp_nolines, width = 4, height = 4, scale = 300, multicore = TRUE)

# 该数据摘自1974年“美国汽车趋势”杂志,包括32种汽车(1973-74型号)的燃油消耗和10个汽车设计和性能方面。#该数据是我们常见的R中的模拟数据 head(mtcars)
mtcars_gg = ggplot(mtcars) + geom_point(aes(x=mpg,color=cyl,y=disp),size=2) + scale_color_continuous(limits=c(0,8)) + ggtitle('mtcars: Displacement vs mpg vs # of cylinders') + theme(title = element_text(size=8), text = element_text(size=12))
plot_gg(mtcars_gg, height=3, width=3.5, multicore=TRUE, pointcontract = 0.7, soliddepth=-200)

准备开始了吗?点击链接 https://github.com/tylermorganwall/rayshader!该网站包含所有`rayhader`功能的文档和示例,可以在`Github`页面上找到实际的存储库。就让你静静的看我有多美! 

想把其它图也用3D 展示,可以拿下面的ggplot2 系列绘图做例子。
|