教你將ggplot2的2D圖像變?yōu)?D

最近無(wú)意間發(fā)現(xiàn)了一個(gè)包:rayshader,這個(gè)包非常有趣,跟大家一起分享。該包的主要功能就是將ggplot2畫出來(lái)的2D圖像變?yōu)?D圖像。廢話就不多說(shuō)了,直接做出來(lái)看看效果吧!

1. 安裝并加載包

install.packages("rayshader")
library(ggplot2)
library(rayshader)
library(viridis)#顏色包

2. 圖1 (2D):

  mtplot = ggplot(mtcars) + 
geom_point(aes(x=mpg,y=disp,color=cyl)) + #畫點(diǎn)
scale_color_continuous(limits=c(0,8))+#設(shè)置顏色尺度從0到8
ggtitle("mtcars: Displacement vs mpg vs # of cylinders") +#添加題目
theme(title = element_text(size=8),#設(shè)置題目字體大小
text = element_text(size=12))#設(shè)置圖片中字體的大小

3. 圖1 (3D):

 plot_gg(mtplot, width=3.5,  sunangle=225)
render_camera(zoom=1,#圖形放大縮小倍數(shù)
theta=30,#旋轉(zhuǎn)角度
phi=30)#方位角, 其實(shí)render_camera類似于改攝像機(jī)位置
render_snapshot()#保存或輸出當(dāng)前視圖
render_snapshot(clear = TRUE)#清除生成的圖片

……耐心等待

4. 圖2 (2D):

ggdiamonds = ggplot(diamonds, aes(x, depth)) +
stat_density_2d(aes(fill = stat(nlevel)),
geom = "polygon", n = 200, bins = 50,contour = TRUE) + #繪制2D密度圖
facet_wrap(clarity~.) + #繪制clarity變量的分組密度圖
scale_fill_viridis_c(option = "C")#使用Viridis顏色梯度(對(duì)色盲友好)

5. 圖2 (3D):

 plot_gg(ggdiamonds,multicore =TRUE,#表示如果光線跟蹤為“真”,則將使用多種顏色來(lái)計(jì)算陰影矩陣
width=5,#寬度
height=5,#高度
scale=250,#3D圖的高度,默認(rèn)是150,設(shè)置得越高圖形越高
windowsize=c(1400,866),
zoom = 0.55, phi = 30)
render_snapshot()#保存或輸出當(dāng)前視圖
render_snapshot(clear = TRUE)

6. 圖3 (2D):

  mtplot_density = ggplot(mtcars) + 
stat_density_2d(aes(x=mpg,y=disp, fill=..density..), geom = "raster", contour = FALSE) +
scale_x_continuous(expand=c(0,0)) +#x的位置尺度
scale_y_continuous(expand=c(0,0)) +#y的位置尺度
scale_fill_gradient(low="pink", high="red")#設(shè)置漸變色
mtplot_density

7. 圖3 (3D):

  plot_gg(mtplot_density, width = 4,zoom = 0.60, theta = -45, phi = 30, 
windowsize = c(1400,866))
render_snapshot()

8. 圖3按照cyl分面繪制 (2D):

  mtplot_density_facet = mtplot_density + facet_wrap(~cyl)

9. 圖3按照cyl分面繪制 (3D):

 plot_gg(mtplot_density_facet)
render_snapshot(clear = TRUE)

今天的內(nèi)容介紹到這,歡迎關(guān)注我們的公眾號(hào):R語(yǔ)言與SPSS學(xué)習(xí)筆記

分享實(shí)用的SPSS及R處理數(shù)據(jù)、分析數(shù)據(jù)及做圖的使用技巧

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容