如何在R Markdown中为球门图片添加文本框展示各位置投篮命中率
嘿,这个需求我刚好折腾过!在R Markdown里给球门图片加定位文本框展示投篮命中率,其实有几个非常实用的路子,我给你拆解下最顺手的几个:
方法1:用ggplot2实现(PDF/HTML通用)
这是我最常用的方法,因为ggplot2的坐标系统好调整,文本框样式也能自定义,输出的图不管是PDF还是HTML都很清晰。步骤很简单:先把球门图片当背景,然后用annotate()添加带框的文本到指定位置。
示例代码:
library(ggplot2) library(png) # 读取你的球门图片(替换成自己的文件路径) goal_img <- readPNG("goal.png") # 创建基础画布,用0-1的相对坐标范围 ggplot() + # 把图片铺满整个画布当背景 annotation_custom(rasterGrob(goal_img), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) + # 添加第一个位置的命中率文本框,坐标根据你的图片实际位置微调 annotate("textbox", x = 0.2, y = 0.7, # 这里的x/y是0-1的相对值,0是左/下,1是右/上 label = "85%", fill = "white", box.color = "black", # 自定义文本框样式 width = unit(0.1, "npc"), height = unit(0.08, "npc")) + # 再加一个示例位置 annotate("textbox", x = 0.5, y = 0.5, label = "72%", fill = "white", box.color = "black", width = unit(0.1, "npc"), height = unit(0.08, "npc")) + # 隐藏坐标轴,让画面只留图片和文本框 theme_void()
方法2:用grid包精细控制(适合PDF输出)
如果你需要更精准的定位,grid包直接操作绘图元素会更灵活。可以用grid.textbox()直接在图片上添加带框文本,还能通过grid.locator()获取点击位置的坐标,非常方便。
示例代码:
library(grid) library(png) # 读取图片 goal_img <- readPNG("goal.png") img_grob <- rasterGrob(goal_img) # 新建绘图页面 grid.newpage() # 先画背景图片 grid.draw(img_grob) # 如果你不知道坐标,先运行grid.locator(),然后点击图片上的位置,会返回对应的x/y值 # grid.locator() # 添加文本框,用相对坐标(npc单位,0-1对应整个绘图区域) grid.textbox("85%", x = unit(0.2, "npc"), y = unit(0.7, "npc"), gp = gpar(fill = "white", col = "black", lwd = 1), # 样式设置 box.width = unit(0.1, "npc"), box.height = unit(0.08, "npc")) grid.textbox("72%", x = unit(0.5, "npc"), y = unit(0.5, "npc"), gp = gpar(fill = "white", col = "black", lwd = 1), box.width = unit(0.1, "npc"), box.height = unit(0.08, "npc"))
方法3:HTML专属的CSS定位法(适合HTML输出)
如果你的R Markdown最终输出是HTML,直接用HTML+CSS定位会更直观,不需要写R代码。把图片放在一个相对定位的容器里,然后文本框用绝对定位,调整百分比就能精准放到对应位置。
示例代码(直接在R Markdown里插入这段HTML):
<div style="position: relative; width: 600px;"> <!-- 插入球门图片,width设为100%让它自适应容器 --> <img src="goal.png" style="width: 100%;"> <!-- 第一个文本框,top和left是相对于容器的百分比 --> <div style="position: absolute; top: 20%; left: 15%; background: white; border: 1px solid black; padding: 5px; font-size: 14px;">85%</div> <!-- 第二个文本框 --> <div style="position: absolute; top: 50%; left: 45%; background: white; border: 1px solid black; padding: 5px; font-size: 14px;">72%</div> </div>
小技巧
- 不管用哪种方法,坐标都需要你根据自己的球门图片实际位置微调,多试几次就能精准定位。
- 如果用ggplot2或grid,
grid.locator()是个神器,运行后点击图片上的点就能直接拿到坐标值,省去瞎猜的麻烦。
内容的提问来源于stack exchange,提问作者Robert Weber
相关产品推荐
相关产品推荐

