如何在R的ggplot排序Likert条形图中添加水平线与分区标注文本?
问题描述
我有一个名为p的ggplot对象,由以下代码生成:
library(dplyr, warn = FALSE) likert_levels <- c( "Strongly disagree", "Disagree", "Neither agree nor disagree", "Agree", "Strongly agree" ) df <- tibble( "there is an argument sort_prop_include_center that could be set up to TRUE in order to include half of the centered level when sorting data" = sample(likert_levels, 150, replace = TRUE), "Similarly, the argument totals_include_center allows you to include half of the centered level into the left and the right totals" = sample(likert_levels, 150, replace = TRUE, prob = 5:1), "Here is one possible option which uses reorder and an ifelse to reorder the variable mapped on y using the counts (aka the sum) of Strictly disagree " = sample(likert_levels, 150, replace = TRUE, prob = 1:5), "and disagree answers. Under the hood ggstats::gglikert reshape the data to long where the question id's are stored in a column named .question and the answers in a column named .answer:" = sample(likert_levels, 150, replace = TRUE, prob = 1:5), "They used sampling data and create a data frame called df. I am using the same as given in the link.(the df not the df_dk). Ok, if i run in R the following code :" = sample(c(likert_levels, NA), 150, replace = TRUE), "proportion of answers higher than the centered level. I want the plot to be sorted according to very left proportions that are the combination (sum) of the two lower levels. (i.e Respectively the percentages on the very right in the sum of the two lower categories. )" = sample(likert_levels, 150, replace = TRUE, prob = c(1, 0, 1, 1, 0)) ) %>% mutate(across(everything(), ~ factor(.x, levels = likert_levels))) library(ggplot2) library(ggstats) p = ggstats::gglikert(df) + aes(y = reorder(.question, ifelse( .answer %in% c("Strongly disagree", "Disagree"), 1, 0 ), FUN = sum ))+ theme(axis.text.y = element_text(size = 8))
我需要为这个排序后的Likert条形图添加两条参考线:
- 在**同意比例20%**的位置添加一条参考线
- 在**同意比例50%**的位置添加第二条参考线
同时在图表面板内的对应区域添加文本标注: - 0-20%同意区域(左侧)标注“warning zone”
- 20%-50%同意区域标注“so-so”
- 50%-100%同意区域(右侧)标注“no warning zone”
解决方案
可以通过ggplot2的geom_vline()添加垂直参考线,结合annotate()添加区域文本标注,实现需求的完整代码如下:
# 在原有p对象基础上添加图层 p_final <- p + # 添加垂直参考线:20%同意对应x=-60,50%同意对应x=0 geom_vline(xintercept = c(-60, 0), linetype = "dashed", color = "gray50") + # 添加区域文本标注 annotate("text", x = -80, y = Inf, label = "warning zone", vjust = 1.5, size = 4) + annotate("text", x = -30, y = Inf, label = "so-so", vjust = 1.5, size = 4) + annotate("text", x = 50, y = Inf, label = "no warning zone", vjust = 1.5, size = 4) # 查看最终图形 print(p_final)
代码说明
参考线设置:
gglikert默认x轴范围为-100到100,对应同意比例从0%到100%(换算公式:同意比例 = (x + 100)/2)。因此20%同意对应x=-60,50%同意对应x=0。用geom_vline()添加虚线样式的灰色参考线,避免干扰主图内容。文本标注设置:
使用annotate()在每个区域的中间位置添加文本:x=-80对应0-20%同意区域的中心x=-30对应20-50%同意区域的中心x=50对应50-100%同意区域的中心y=Inf将文本固定在图表顶部,vjust=1.5调整文本位置使其位于参考线上方,size控制文本大小。
内容的提问来源于stack exchange,提问作者Homer Jay Simpson
相关产品推荐
相关产品推荐

