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

如何调整R中ggplot2绘制的Venn图集合名称位置?

解决ggvenn集合名称位置调整问题

方法一:利用ggvenn自带参数set_name_position

geom_venn内置了set_name_position参数,可直接指定集合名称的位置,无需调整整个图层的position,能避免Venn图偏移问题。该参数支持的预设位置包括"top"(默认)、"bottom"、"left"、"right",也可传入坐标向量自定义位置。

修改后的代码示例:

#libraries
library(ggplot2)
library(dplyr)
library(ggvenn)

#Create dataset
name <- c(1:18)
itt <- c("FALSE","TRUE","FALSE","TRUE","FALSE","TRUE","TRUE","FALSE","FALSE","FALSE","TRUE","FALSE","TRUE","TRUE","FALSE","FALSE","FALSE","TRUE")
ost <- c("FALSE","TRUE","FALSE","TRUE","FALSE","FALSE","FALSE","TRUE","TRUE","TRUE","TRUE","FALSE","TRUE","TRUE","TRUE","TRUE","TRUE","TRUE")
M <- tibble(name,itt,ost)
M <- M %>% mutate_at(c("itt","ost"),as.logical)

#Use ggplot to create Venn Diagram
ggplot(M,aes(A=ost, B=itt))+
  geom_venn(set_name_size = 4, auto_scale=TRUE,
            set_names=c("ID on OST","IR on ITT"),
            fill_color = c("firebrick","darkgray"),fill_alpha = 0.65,
            show_percentage = FALSE,show_outside="none",
            set_name_position = c("left", "right")) # 将集合名称分别放在左侧和右侧
  ggtitle("Placebo Group")+
  coord_fixed()+
  theme_void()+theme(plot.title = element_text(hjust=0.5,vjust=-5))

若要将名称放在底部,只需把set_name_position改为c("bottom", "bottom")即可。

方法二:手动添加标签(更灵活的自定义)

如果自带参数无法满足需求,可以关闭ggvenn的自带标签,用annotate()手动添加文本,实现对位置的完全控制:

ggplot(M,aes(A=ost, B=itt))+
  geom_venn(set_name_size = 4, auto_scale=TRUE,
            set_names=c("",""), # 清空自带标签
            fill_color = c("firebrick","darkgray"),fill_alpha = 0.65,
            show_percentage = FALSE,show_outside="none")+
  # 手动添加标签,x和y坐标可根据实际图面调整
  annotate("text", x = -1.2, y = 0, label = "ID on OST", size=4)+
  annotate("text", x = 1.2, y = 0, label = "IR on ITT", size=4)+
  ggtitle("Placebo Group")+
  coord_fixed()+
  theme_void()+theme(plot.title = element_text(hjust=0.5,vjust=-5))

这种方法可以自由调整标签的x、y坐标,精准控制位置,且不会影响Venn图本身的布局。

注意事项

  • 不要使用图层的position参数调整标签位置,该参数用于调整整个geom图层的位置,会导致Venn图偏移。
  • 若使用set_name_position的自定义坐标,比如set_name_position = list(c(-1,0), c(1,0)),可更精准地定位每个标签的位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 14:37:21