ggplot如何根据变量类型为geom_text设置不同位置对齐方式
实现方法
你可以通过将对齐参数映射到类别变量的方式,为不同类别的标签单独设置对齐规则,无需拆分图层,修改逻辑如下:
- 你绘制的是水平堆叠条形图,文本水平方向对齐使用
hjust参数(垂直对齐才用vjust,注意不要混淆) - 在
geom_text的美学映射里新增hjust = variable,将对齐规则和变量类别绑定 - 新增
scale_hjust_manual()指定每个类别对应的对齐值即可
修改后的完整代码:
(empilhado<-ggplot(dfm, aes(y = Year, x = abs(value), fill = variable)) + scale_x_continuous(sec.axis = sec_axis(trans = ~.*1, name="Trab."), expand=expansion(mult=c(0,0.05)))+ geom_col(data = rotulo, aes(y = Year, x=abs(trabalho), fill=NULL), width = .7, colour="black", lwd=0.1, position = "fill", orientation = "y") + geom_label(data = rotulo, aes(y= Year, x = abs(trabalho), fill=NULL, label=paste(format(round(trabalho, digits=0), nsmall=0, decimal.mark=",", big.mark="."), format(round(aprovado, digits=0), nsmall=0, decimal.mark=",", big.mark="."))), color="black", size=4, position = position_fill(vjust=1.06)) + geom_col(width = .7, colour="black", lwd=0.1, position = "fill", orientation = "y") + # 新增hjust映射到variable变量 geom_text(aes(label=format(round(value, digits=0), nsmall=0, decimal.mark=",", big.mark="."), hjust = variable), size=4, color="white", position = position_fill(vjust=0.5)) + theme(panel.grid.major = element_line(colour = "gray90",size=0.75), panel.grid.minor = element_line(colour = "gray90",size=0.75), legend.position="top", axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.x = element_blank(), panel.background = element_blank())+ scale_fill_manual(values = c("#000000","tomato","blue")) + # 按类别指定对齐值,注意键名要和数据中variable的实际取值完全一致 scale_hjust_manual(values = c("Marionete" = 0, "Pedido" = 0.5, "Fatura" = 1)) )
如果最终效果里标签太贴近条形块边缘,可以微调对应数值,比如把Marionete的hjust改成0.1,Fatura的改成0.9,避免文字超出块的显示范围。
内容的提问来源于stack exchange,提问作者Diogo Tasquin Reducino
相关产品推荐
相关产品推荐

