如何在ggplot中扩展轴范围至-60~60并显示全部正刻度值
问题描述
我有如下数据集:
structure(list(name = structure(11:1, .Label = c("Control_over_life", "Access_mentalhealthcare", "Access_physicalhealthcare", "Use_health_care", "Use_mental_health_care", "Alcohol_consumption", "Fear_healthcare", "Anger", "Social_isolation", "Anxiety", "Stress"), class = c("ordered", "factor")), value = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L), .Label = c("Increased ", "No change", "Decreased " ), class = "factor"), n = c(152L, 148L, 128L, 88L, 76L, 56L, 73L, 75L, 81L, 92L, 107L), per = c(58, 57, 49, 34, 29, 22, -28, -29, -31, -35, -41), group = c("Increased", "Increased", "Increased", "Increased", "Increased", "Increased", "Decreased", "Decreased", "Decreased", "Decreased", "Decreased")), row.names = c(NA, -11L ), class = c("tbl_df", "tbl", "data.frame"))
使用以下代码绘制图表:
full$name <- factor(full$name , levels = rev(unique(full$name )), ordered=TRUE) ggplot(full, aes(x = name, y = per, fill = group)) + geom_bar(stat = "identity") + coord_flip() + theme_bw() + xlab("Stressor") + ylab("Percentage") + scale_y_continuous(breaks = pretty(full$per), labels = abs(pretty(full$per)))
当前图表的Y轴范围是(-40,60),希望将轴范围调整为(-60到60),同时保留全部正数值的显示,该如何实现?
解决方案
你可以通过修改scale_y_continuous的limits参数指定轴范围,同时调整刻度参数保证显示合理,具体代码如下:
full$name <- factor(full$name , levels = rev(unique(full$name )), ordered=TRUE) ggplot(full, aes(x = name, y = per, fill = group)) + geom_bar(stat = "identity") + coord_flip() + theme_bw() + xlab("Stressor") + ylab("Percentage") + scale_y_continuous( limits = c(-60, 60), # 强制设置Y轴范围为-60到60 breaks = seq(-60, 60, by = 20), # 自定义刻度间隔为20 labels = abs(seq(-60, 60, by = 20)) # 刻度显示绝对值 )
补充说明
limits = c(-60, 60)直接扩展了负轴范围,同时你的正数值最大值为58,完全在60的范围内,不会被截断。- 如果你想保留
pretty()生成的自然刻度,也可以替换成以下写法:
scale_y_continuous( limits = c(-60, 60), breaks = pretty(c(-60, 60)), labels = abs(pretty(c(-60, 60))) )
内容的提问来源于stack exchange,提问作者Ali Roghani
相关产品推荐
相关产品推荐

