ggplot中Y轴标签偏移(部分右对齐部分左对齐)的问题排查
解决ggplot2中Y轴标签对齐不一致的问题
问题原因
你代码里的axis.text.y = element_text(vjust = 1, hjust=-1)是导致对齐错位的核心:
hjust=-1是基于文本自身宽度进行偏移,两位数标签(如90)和三位数标签(如100)的文本宽度不同,偏移后视觉上就出现了"100及以上右对齐、90及以下左对齐"的错位效果。
解决方案
用右对齐+边距控制替代直接用hjust偏移,确保所有标签以Y轴为基准统一对齐,同时可灵活调整标签与轴的距离:
修改theme中的axis.text.y参数:
axis.text.y = element_text(vjust = 1, hjust = 1, margin = margin(r = 15))
hjust=1:让所有Y轴标签的右边缘对齐到Y轴位置,统一对齐基准margin(r = 15):通过设置标签右侧边距,控制标签与Y轴的距离,数值可按需调整
修改后的完整代码
test <- ggplot(data, aes(x=Month, y=Value, color=Name, group=Name, fill=Name))+ geom_line(size=3)+ geom_point(size=5)+ scale_color_manual(values=c("#FBE785","#0F5F00","#FFC300","#1BFFAA"))+ ylab ("")+ xlab ("")+ labs(caption = paste("Fonte: Fred e IBGE.")) + scale_x_date(date_labels = "%b/%y", breaks = "6 month", expand=c(0,0))+ coord_cartesian(clip = "off")+ theme_minimal() + guides(fill=guide_legend())+ theme(panel.background = element_rect(fill= "#122929",color = "#122929"), plot.background = element_rect(fill = "#122929"), panel.grid.major = element_line(color = "#4D4B55", size =0.1), panel.grid.minor = element_line(color= "#4D4B55", size =0.1), panel.grid = element_blank(), axis.text.y = element_text(vjust = 1, hjust = 1, margin = margin(r = 15)), # 修改此行 axis.text.x = element_text(vjust = -1, hjust=0), legend.title = element_blank(), legend.position = "bottom", legend.key.width = unit(1.5, "cm"), plot.caption = element_text(family = "Abel",vjust = -1, hjust = 0,colour="#4D4B55", size= 30), text = element_text(family = "Abel", color = "#4D4B55",size = 35), plot.margin = margin(1,1,1.5,1.2, "cm")) ggsave("./test.png", width = 21, height = 15, dpi = 300)
内容的提问来源于stack exchange,提问作者Leonardo Dutra
相关产品推荐
相关产品推荐

