如何用plot_gg实现ggplot2仅点3D化、文本标签不3D的可视化?
解决rayshader中仅让点3D化、文本标签保持2D的问题
方法1:分离图层渲染
rayshader的plot_gg默认会对所有图层应用3D转换,要实现点3D、文本2D,可拆分渲染流程:
- 先生成不含文本标签的基础ggplot对象(移除
geom_text()/geom_label()及轴标签、标题等文本元素) - 用
plot_gg渲染该基础图得到3D场景,保存快照 - 单独生成仅含文本的图层,通过图像合成工具(如
magick)叠加到3D快照上
示例代码:
# 1. 创建不含文本的基础绘图 plot_cities_no_text <- plot_cities %>% theme(plot.title = element_blank(), axis.text = element_blank(), axis.title = element_blank()) %>% # 确保仅保留点图层,移除所有文本相关图层 geom_point(aes(color = your_color_var)) # 替换为你的点图层参数 # 2. 渲染3D场景并保存快照 plot_gg(plot_cities_no_text , width=4.0 , height = 4.0 , multicore = TRUE , windowsize = c(1400,866) , sunangle=225 , zoom = 0.60 , phi = 30 , theta = 45 , emboss_text = 0 ) render_snapshot(filename = "3d_base.png") # 3. 叠加文本图层 library(magick) base_img <- image_read("3d_base.png") # 生成仅含文本的图层(点设为透明,背景设为空白) text_layer <- image_ggplot( plot_cities %>% geom_point(color = "transparent") %>% theme(panel.background = element_blank(), plot.background = element_blank()) ) final_img <- image_composite(base_img, text_layer, offset = "+0+0") image_write(final_img, "3d_with_2d_text.png")
方法2:通过height_aes指定仅拉伸点图层
利用plot_gg的height_aes参数,仅让点图层映射高度,文本图层不设置高度属性:
- 在ggplot的点图层中添加
aes(height = ...)映射(可使用点的大小、自定义数值等作为高度变量) - 调用
plot_gg时指定height_aes = "height",这样只有带height映射的点会被3D拉伸,文本保持平面
示例代码:
# 修改ggplot,给点图层添加height映射 plot_cities_3d_points <- plot_cities + geom_point(aes(height = your_height_variable)) # 替换为你的高度变量(如点的size值) # 文本图层保持原样,不添加height映射 # 渲染3D图 plot_gg(plot_cities_3d_points , width=4.0 , height = 4.0 , multicore = TRUE , windowsize = c(1400,866) , sunangle=225 , zoom = 0.60 , phi = 30 , theta = 45 , emboss_text = 0 , height_aes = "height" # 仅对含height aes的图层应用3D拉伸 )
内容的提问来源于stack exchange,提问作者Rhea Ramtohul
相关产品推荐
相关产品推荐

