首页 > 解决方案 > 当margin、hjust 和vjust 无法按照您想要的方式定位条形图标签时,您会怎么做?

问题描述

我知道那里有一百万个这样的问题,但我很难找到对我有帮助的问题。

这是一个简单的代表:

library(ggplot2)
library(ggpubr)
library(gridExtra)
ex.table <- structure(c(CAT1 = 0, CAT2 = 318, CAT3 = 21, CAT4 = 1897,CAT5 = 301, CAT6 = 643, CAT7 = 770, CAT8 = 120, CAT9 = 43), .Dim = 9L, .Dimnames = list(c("CAT1", "CAT2", "CAT3", "CAT4", "CAT5", "CAT6", "CAT7", "CAT8", "CAT9")))

我绘制它:

p <- ggplot() +
  geom_bar(aes(x=names(ex.table), y=ex.table), stat="identity") +
  ylab("Some Number") +
  xlab("") +
  scale_x_discrete(labels=c("Lots of words, \nalmost too many to function with", "Few words", "Fewer but still a few", "Blah", "Blah blah", "Lots of words again \njust because I need more", "The quick brown fox jumps", "Over the", "Lazy dog"))

p + theme(axis.text.x=element_text(angle = 45, hjust=.8, margin = margin(t=25), colour = "black"))

问题 我如何左对齐多行标签的顶行(类似于hjust=0),并将标签向左移动,使标签的末端与刻度线对齐(类似于hjust=1)...hjust 、 vjust 和 margin 并没有解决我的问题。谁能帮我微调这些标签?

如果我调整margin并离开hjust=0,我会得到对齐不正确但格式正确的标签:

p + theme(axis.text.x=element_text(angle = 45, hjust=0, margin=margin(t=100), colour = "black"))

如果我调整 hjust,我会失去我想要的理由,但位置很好:

p + theme(axis.text.x=element_text(angle = 45, hjust=1, colour = "black"))

在这个例子中,如果我以不同的方式分隔换行符,我可以到达那里,但我想知道如何移动这些标签。我的理想输出类似于上面的最后一行代码,但所有顶行文本都是左对齐的。我可以做吗?

谢谢你的帮助。

标签: rggplot2

解决方案


推荐阅读