一個震撼的交互型3D可視化R包 - rayshader作者:張虎 協(xié)和 編輯:陳同 生信寶典 
雖然3D 的plot見得比較多了,但是看見這樣的R包 ,我的心還是砰了一下,這個簡直不能再好看了! 關(guān)鍵是!??!敲黑板,這個R 包超簡單!?。τ趧倢W(xué)習(xí)R語言的同學(xué)們來說,會被圈粉噠! 該包的主要功能就是將ggplot2畫出來的2D 圖像變?yōu)?code>3D圖像,不說廢話,直接上代碼。 # 安裝rayshader包 install.packages('remote') remotes::install_github('tylermorganwall/rayshader') library(rayshader) library(ggplot2)
# 查看數(shù)據(jù)格式 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顏色設(shè)置為“巖漿”色,簡稱為“A”,共有“A”,“B”,“C”,“D”和“E”五種;gg # 繪制2D圖
# 轉(zhuǎn)成3D圖,只需要plot_gg函數(shù)即可 plot_gg(gg,multicore=TRUE,width=5,height=5,scale=250)

打開后,可以像任何其他光線圖一樣操作繪圖 - 可以調(diào)用render_camera() 以編程方式更改攝像機(jī)位置,render_snapshot() 可以保存或輸出當(dāng)前視圖,甚至可以使用render_depth() 來渲染光滑深度場效應(yīng)。還可以更改甚至刪除光源,并將任何參數(shù)傳遞給plot_gg() ,繪制為plot_3d() 。 # 如果缺失sf包,建議先安裝 library(sf)
nc = st_read(system.file('shape/nc.shp', package='sf'), quiet = TRUE) #加載包自帶的數(shù)據(jù) gg_nc = ggplot(nc) + # 加載North Carolina地圖 geom_sf(aes(fill = AREA)) + # 繪制地理數(shù)據(jù)模型,sf對象,全稱Simple feature scale_fill_viridis('Area') + # 按區(qū)域上色 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)

# 隨機(jī)取三組數(shù)字,并且對其進(jìn)行合并,兩列,一列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) #其實如果我們有相同類型的數(shù)據(jù),也可以仿照該組織方式進(jìn)行合并;# 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)

# 該數(shù)據(jù)摘自1974年“美國汽車趨勢”雜志,包括32種汽車(1973-74型號)的燃油消耗和10個汽車設(shè)計和性能方面。#該數(shù)據(jù)是我們常見的R中的模擬數(shù)據(jù) 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)

準(zhǔn)備開始了嗎?點擊鏈接 https://github.com/tylermorganwall/rayshader!該網(wǎng)站包含所有`rayhader`功能的文檔和示例,可以在`Github`頁面上找到實際的存儲庫。就讓你靜靜的看我有多美! 

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