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

如何在ggplot2绘图的caption前添加橙色方形图形

解决方案

要在ggplot的caption文本前添加和图中一致的橙色方形(shape=22),可以用两种简单方法实现,同时先修正你代码里的小错误:library(ggplot)需改为library(ggplot2),否则会报错。

方法一:Unicode字符快速实现

直接在caption文本前插入Unicode实心方块符号\U25A0,配合你设置的橙色文本颜色,就能得到匹配的视觉效果:

library(ggplot2)
mycolor <- c("firebrick", "green")
intervention_labels <- c("Control", "Case")
xlab <- c("Baseline", "Week 1", "Week 2", "Week 3", "Week 4", "End")
ggplot(datanishatlong, aes(x=time, y=vas, color = intervention)) + 
  geom_point(position = position_jitterdodge(dodge.width = 0.8, jitter.height = 0.2, jitter.width = 0.2), alpha = 0.5, size = 2) + 
  geom_point(stat = "summary", fun = "mean", size = 4, shape = 22, position = position_dodge(width = 0.8), alpha = 0.5, show.legend = F, fill = "orange") + 
  scale_color_manual(values = mycolor, labels = intervention_labels) + 
  theme_minimal() +
  labs(x="Time", y="VAS", title = "VAS across follow-up times", color = "Intervention", caption = "\U25A0 Squares represent mean value") +
  theme(plot.caption = element_text(size=6, color="orange", face="italic")) +
  scale_x_discrete(labels = xlab)

方法二:添加精确匹配的shape=22图形

如果需要和图中shape=22的带边框橙色方块完全一致,可借助grid包创建图形对象,再通过annotation_custom添加到caption位置:

library(ggplot2)
library(grid)

mycolor <- c("firebrick", "green")
intervention_labels <- c("Control", "Case")
xlab <- c("Baseline", "Week 1", "Week 2", "Week 3", "Week 4", "End")

# 创建匹配的橙色方形grob
square_grob <- pointsGrob(
  x = unit(0.01, "npc"), y = unit(0.5, "npc"),
  pch = 22, size = unit(6, "pt"),
  gp = gpar(fill = "orange", alpha = 0.5, col = "black")
)

ggplot(datanishatlong, aes(x=time, y=vas, color = intervention)) + 
  geom_point(position = position_jitterdodge(dodge.width = 0.8, jitter.height = 0.2, jitter.width = 0.2), alpha = 0.5, size = 2) + 
  geom_point(stat = "summary", fun = "mean", size = 4, shape = 22, position = position_dodge(width = 0.8), alpha = 0.5, show.legend = F, fill = "orange") + 
  scale_color_manual(values = mycolor, labels = intervention_labels) + 
  theme_minimal() +
  labs(x="Time", y="VAS", title = "VAS across follow-up times", color = "Intervention", caption = "Squares represent mean value") +
  theme(
    plot.caption = element_text(size=6, color="orange", face="italic", margin = margin(t=10)),
    plot.caption.position = "plot"
  ) +
  scale_x_discrete(labels = xlab) +
  annotation_custom(square_grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = -Inf)

通过调整unit参数,可按需控制方形的位置和大小。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:37:33