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

在R语言中用ggplot2为Likert图表添加区域标注文本

实现Likert条形图的警告区标注

要完成你需要的效果,我们可以直接基于likert.bar.plot返回的ggplot对象进行扩展,添加区域划分和文本注释,具体步骤如下:

修正后的完整代码

library(tidyverse)
library(likert)

# 加载并处理数据集
data(pisaitems) 
items28 <- pisaitems[, substr(names(pisaitems), 1, 5) == "ST24Q"] 
items28[items28 == "Agree"] <- "Disagree"
df <- items28[1:50,]

# 生成Likert条形图并添加标注
p <- likert::likert.bar.plot(df) +
  # 添加警告区与无警告区的分隔虚线
  geom_vline(xintercept = -95, linetype = "dashed", colour = "grey20") +
  # 左侧警告区添加红色水平文本
  annotate("text", x = -97.5, y = nrow(df) + 0.5, 
           label = "Warning Zone", color = "red", 
           size = 3, fontface = "bold", angle = 0) +
  # 左侧无警告区添加垂直文本
  annotate("text", x = -50, y = nrow(df) + 0.5, 
           label = "No Warning Zone", color = "black", 
           size = 3, fontface = "bold", angle = 90) +
  # 扩展x轴范围避免文本被截断
  xlim(-105, 100)

print(p)

关键细节说明

  • 区域划分逻辑:用geom_vline在x=-95处添加虚线,将左侧-100到-95区间对应为95%-100%的占比警告区,-95到0区间对应0%-96%的无警告区。
  • 文本定位:
    • Warning Zone放在警告区中间位置(x=-97.5),水平显示,用红色突出警告属性。
    • No Warning Zone放在左侧无警告区的中间位置(x=-50),垂直显示保证布局美观。
  • 适配调整:通过xlim扩展x轴左侧范围,确保注释文本完整显示。若你需要将警告区设置在右侧95%-100%区间,只需把annotate的x坐标改为97.5,并调整分隔线到x=95即可。

内容的提问来源于stack exchange,提问作者Homer Jay Simpson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:20:18