可自由缩放的小平面上的左调整(hallow = 0)垂直x轴标签 [英] Left-adjust (hjust = 0) vertical x axis labels on facets with free scale

查看:80
本文介绍了可自由缩放的小平面上的左调整(hallow = 0)垂直x轴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已决定重新表述此问题. (编辑将花费更多时间,并且我认为也不会对OP有所帮助.)

I have decided to rephrase this question. (Editing would have taken more time and in my opinion would also not have helped the OP.)

scale = 'free_x'时,如何在小平面上进行一个左调整(hjust = 0,即沿文本方向)?

How can one left-adjust (hjust = 0, i.e., in text direction) over facets, when scale = 'free_x'?

我并不是真的认为x标签的左调整不是必须要做的事情(长标签通常很难读取,而右调整则可能是更好的选择)-但是我发现这个问题足够有趣.

I don't really think that left-adjustment of x-labels is a very necessary thing to do (long labels generally being difficult to read, and right-adjusting probably the better choice) - but I find the problem interesting enough.

我尝试使用空填充来最大字符长度,但这并不能使所有字符串的长度都相同.同样,设置axis.text.x = element.text(margin = margin())也无济于事.不用说,hjust = 0没有帮助,因为它在每个方面都在调整.

I tried with empty padding to the maximum character length, but this doesn't result in the same length for all strings. Also, setting axis.text.x = element.text(margin = margin()) doesn't help. Needless to say, hjust = 0 does not help, because it is adjusting within each facet.

library(ggplot2)

diamonds$cut_label <- paste("Super Dee-Duper", as.character(diamonds$cut))

ggplot(data = diamonds, aes(cut_label, carat)) +
  facet_grid(~ cut, scales = "free_x") +
  theme(axis.text.x = element_text(angle = 90))

红色箭头和虚线指示标签应如何调整. hjust = 0margins或空白填充不会导致在所有方面调整这些标签.

The red arrows and dashed line indicate how the labels should adjust. hjust = 0 or margins or empty padding do not result in adjustment of those labels over all facets.

来自这个著名问题的数据修改

推荐答案

我们可以在生成绘图后使用library(grid)编辑文本grob.

We can edit the text grobs after generating the plot, using library(grid).

g <- ggplot(data = diamonds, aes(cut_label, carat)) +
  facet_grid(~cut, scales = "free_x") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

gt <- cowplot::as_gtable(g)
axis_grobs <- which(grepl("axis-b", gt$layout$name))
labs <- levels(factor(diamonds$cut_label))[order(levels(diamonds$cut))]

for (i in seq_along(axis_grobs)) {
  gt$grobs[axis_grobs[i]][[1]] <-
    textGrob(labs[i], y = unit(0, "npc"), just = "left", rot = 90, gp = gpar(fontsize = 9))
}

grid.draw(gt)

这篇关于可自由缩放的小平面上的左调整(hallow = 0)垂直x轴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆