如何在R的ggplot图形外添加类AutoCAD样式的标题栏?
嘿,这个需求完全可以实现!我自己也做过类似的工程图风格ggplot,给你分享几个实用的方案,都是用R原生或者常用包就能搞定的:
方案1:用ggplot原生工具快速实现
这个方案最直接,不需要额外安装太多包,靠annotate和theme就能搞定黑色边框+底部标题栏:
library(ggplot2) # 先绘制你的基础图形 base_plot <- ggplot(mtcars, aes(mpg, hp)) + geom_point() + # 设置整体黑色边框 theme( panel.border = element_rect(color = "black", fill = NA, size = 1), # 给底部标题栏预留空间 plot.margin = margin(10, 10, 50, 10) ) # 添加标题栏(支持多矩形分割) final_plot <- base_plot + # 标题栏背景(如果要分块,就拆成多个rect) annotate("rect", xmin = -Inf, xmax = 15, ymin = -Inf, ymax = 50, fill = "gray90", color = "black") + annotate("rect", xmin = 15, xmax = 25, ymin = -Inf, ymax = 50, fill = "gray80", color = "black") + annotate("rect", xmin = 25, xmax = Inf, ymin = -Inf, ymax = 50, fill = "gray90", color = "black") + # 标题栏文本 annotate("text", x = 7.5, y = 30, label = "图号: PLOT-001", size = 3) + annotate("text", x = 20, y = 30, label = "制图: Melanie", size = 3) + annotate("text", x = 32, y = 30, label = "日期: 2024-05-20", size = 3) + # 调整y轴范围,避免标题栏覆盖数据点 ylim(50, 350) print(final_plot)
小提示:如果不需要分块标题栏,把三个rect合并成一个就行,颜色也可以自定义成你需要的工程图风格。
方案2:用grid包实现更精准的布局
如果想要更灵活控制标题栏的位置和尺寸,grid包是绝佳选择,它能把主体图形和标题栏当成独立的图形对象拼接:
library(ggplot2) library(grid) # 基础图形(这次不需要留底部margin) base_plot <- ggplot(mtcars, aes(mpg, hp)) + geom_point() + theme( panel.border = element_rect(color = "black", fill = NA, size = 1), plot.margin = margin(10, 10, 0, 10) ) # 创建标题栏的图形对象(支持复杂排版) title_bar <- grobTree( # 标题栏背景分块 rectGrob(x = 0.25, width = 0.5, gp = gpar(fill = "gray90", col = "black")), rectGrob(x = 0.75, width = 0.5, gp = gpar(fill = "gray80", col = "black")), # 文本内容 textGrob("图号: PLOT-001", x = 0.25, y = 0.5, gp = gpar(fontsize = 10)), textGrob("制图/日期: Melanie | 2024-05-20", x = 0.75, y = 0.5, gp = gpar(fontsize = 10)) ) # 组合图形和标题栏 grid.newpage() pushViewport(viewport(layout = grid.layout(2, 1, heights = unit(c(9, 1), "null")))) print(base_plot, vp = viewport(layout.pos.row = 1, layout.pos.col = 1)) grid.draw(title_bar, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))
这个方案适合需要精细调整标题栏比例、位置的场景,比如标题栏占整体图的1/10高度,完全由你控制。
方案3:用patchwork包快速拼接
如果你已经在用patchwork组合图形,那可以直接把标题栏做成一个空的ggplot,然后和主体图上下拼接:
library(ggplot2) library(patchwork) # 基础图形 base_plot <- ggplot(mtcars, aes(mpg, hp)) + geom_point() + theme( panel.border = element_rect(color = "black", fill = NA, size = 1), plot.margin = margin(10, 10, 0, 10) ) # 标题栏专用ggplot(去掉所有冗余元素) title_bar_plot <- ggplot() + annotate("rect", xmin = 0, xmax = 3, ymin = 0, ymax = 1, fill = "gray90", color = "black") + annotate("text", x = 0.5, y = 0.5, label = "图号: PLOT-001") + annotate("text", x = 1.5, y = 0.5, label = "制图: Melanie") + annotate("text", x = 2.5, y = 0.5, label = "日期: 2024-05-20") + theme_void() # 上下拼接,设置高度比例 base_plot / title_bar_plot + plot_layout(heights = c(9, 1))
这个方案的优势是代码简洁,和你平时用patchwork组合图形的逻辑一致,容易上手。
内容的提问来源于stack exchange,提问作者Melanie Walling
相关产品推荐
相关产品推荐

