如何将棒棒糖图转为垂直棒棒糖图并修复Y轴标签重叠问题
垂直棒棒糖图转换与标签重叠修复方案
关键修改说明
- 转垂直布局:直接移除原代码中的
coord_flip()函数,让图表回到垂直形态 - 修复标签重叠:删除原代码中导致标签向左偏移的
axis.text.y负margin设置,同时调整x轴分类标签的角度和对齐方式,解决长标签拥挤问题
修改后的完整代码
library(ggplot2) library(ggalt) library(scales) df = read.csv(text="category,pct Other,0.09 South Asian/South Asian Americans,0.12 Interngenerational/Generational,0.21 S Asian/Asian Americans,0.25 Muslim Observance,0.29 Africa/Pan Africa/African Americans,0.34 Gender Equity,0.34 Disability Advocacy,0.49 European/European Americans,0.52 Veteran,0.54 Pacific Islander/Pacific Islander Americans,0.59 Non-Traditional Students,0.61 Religious Equity,0.64 Caribbean/Caribbean Americans,0.67 Latino/Latina,0.69 Middle Eastern Heritages and Traditions,0.73 Trans-racial Adoptee/Parent,0.76 LBGTQ/Ally,0.79 Mixed Race,0.80 Jewish Heritage/Observance,0.85 International Students,0.87", stringsAsFactors = FALSE, sep = ",", header=TRUE) gg = ggplot(df, aes(reorder(category, pct), pct)) gg = gg + geom_lollipop(point.colour="steelblue", point.size=3) gg = gg + scale_y_continuous(expand=c(0,0), labels=percent, breaks=seq(0, 1, by=0.2), limits=c(0, 1)) # 移除水平翻转,使用垂直布局 gg = gg + labs(x=NULL, y=NULL, title="纽约州立大学科特兰分校多元文化校友调查结果", subtitle="按种族、族裔、祖籍及关注方向排序的核心关切领域", caption="数据来源:stephanieevergreen.com") gg = gg + theme_minimal(base_family="Arial Narrow") # 垂直图中隐藏x轴主网格线 gg = gg + theme(panel.grid.major.x=element_blank()) gg = gg + theme(panel.grid.minor=element_blank()) # 调整x轴标签:旋转45度右对齐,设置margin避免与图表重叠 gg = gg + theme(axis.text.x=element_text(angle=45, hjust=1, margin=margin(t=5))) # 替换为x轴基线设置,删除原导致重叠的y轴标签负margin gg = gg + theme(axis.line.x=element_line(color="#2b2b2b", size=0.15)) gg = gg + theme(plot.margin=unit(rep(30, 4), "pt")) gg = gg + theme(plot.title=element_text(face="bold")) gg = gg + theme(plot.subtitle=element_text(margin=margin(b=10))) gg = gg + theme(plot.caption=element_text(size=8, margin=margin(t=10))) gg
最终效果
- 图表变为垂直布局,每个分类的棒棒糖从x轴向上延伸
- x轴长标签通过旋转对齐解决拥挤问题,同时保持与图表主体的间距
- 彻底消除了标签与线条重叠的问题
内容的提问来源于stack exchange,提问作者Ed_Gravy
相关产品推荐
相关产品推荐

