You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot文本旁添加自定义形状:左侧正方形与底部矩形条

在ggplot文本旁添加自定义形状(正方形+底部矩形条)

我有一段生成哑铃图的ggplot代码:

library(ggplot2)
library(ggalt)
library(ggpp)
df <- data.frame(trt=LETTERS[1:5], l=c(20, 40, 10, 30, 50), r=c(70, 50, 30, 60, 80))

ggplot(df, aes(y=trt, x=l, xend=r)) +
  geom_text_npc(aes(npcx = 'center', npcy = 'bottom'), label = expression('No. of'~italic('AA')~'isolates with corresponding types'), parse = TRUE) +
  geom_dumbbell(aes(x = 'center', y = 'bottom'),
                size=3, color="#e3e2e1",
                colour_x = "#5b8124", colour_xend = "#bad744")

现在需要给顶部的文本添加两个自定义元素:

  • 文本左侧添加一个正方形
  • 文本底部添加一个矩形条(不用下划线,因为无法调整宽度和与文本的间距,之前尝试geom_dumbbell没得到理想效果)

解决方案

可以利用ggpp的npc坐标系统,结合geom_tile_npc和geom_rect_npc精准定位这两个形状,代码如下:

library(ggplot2)
library(ggalt)
library(ggpp)
df <- data.frame(trt=LETTERS[1:5], l=c(20, 40, 10, 30, 50), r=c(70, 50, 30, 60, 80))

ggplot(df, aes(y=trt, x=l, xend=r)) +
  # 绘制底部矩形条
  geom_rect_npc(
    aes(xmin = 0.35, xmax = 0.65, ymin = 0.02, ymax = 0.03),
    fill = "#e3e2e1", color = NA
  ) +
  # 绘制左侧正方形
  geom_tile_npc(
    aes(npcx = 0.32, npcy = 0.06),
    width = 0.02, height = 0.02,
    fill = "#5b8124", color = NA
  ) +
  # 原有文本(调整对齐方式)
  geom_text_npc(
    aes(npcx = 0.35, npcy = 0.06), 
    label = expression('No. of'~italic('AA')~'isolates with corresponding types'), 
    parse = TRUE,
    hjust = 0
  ) +
  # 原有哑铃图
  geom_dumbbell(
    size=3, color="#e3e2e1",
    colour_x = "#5b8124", colour_xend = "#bad744"
  ) +
  # 调整顶部边距避免文本截断
  theme(plot.margin = margin(15, 5, 5, 5))

关键细节说明

  • geom_rect_npc:通过xmin/xmax控制矩形条的宽度,ymin/ymax控制高度和与文本的垂直间距,颜色可按需调整
  • geom_tile_npc:通过npcx/npcy定位正方形到文本左侧,width/height控制正方形大小,填充色和哑铃图左端点保持统一
  • 文本设置hjust=0实现左对齐,配合plot.margin调整顶部边距,避免元素重叠或截断

内容的提问来源于stack exchange,提问作者Brian Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:53:08