ggplot2:yaxis标签未在各个方面对齐 [英] ggplot2: yaxis labels not aligning across facets

查看:416
本文介绍了ggplot2:yaxis标签未在各个方面对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ggplot中的各个面上对齐轴标签时遇到了一些麻烦.我试图使所有y轴标签左对齐,以使文本看起来更均匀,但是在脚本中添加"scales = free"参数之后,标签仅在内对齐方面.我已经用一些伪代码进行了测试,并且发生了相同的问题:

I'm having some trouble aligning axis labels across facets in ggplot. I'm trying to left align all of the y-axis labels to make the text look more uniform, but the moment the "scales = free" argument is added to the script, the labels only become aligned within the facet. I've tested with some dummy code and the same issue occurs:

test <- data.frame(label = c('a', 'ab', 'a', 'abc', 'abcd', 'abcde', 
                             'abcdef', 'abcdefg', 'abcdefgh', 
                             'abcdefghi', 'abcdefghij', 
                             'abcdefghijkfiutdkjgbhcvi'),
                   xdum = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
                   facett = rep(c("Facet 1", "Facet 2", "Facet 3"), 4), 
                   data = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))

ggplot(test, aes(x = xdum, y = label, label = data)) + 
  facet_grid(facett~., scales = "free", space = "free") + 
  geom_tile() + 
  theme(axis.ticks = element_blank(), axis.text.y = element_text(hjust = 0))

有人以前见过这个,找到了解决方法吗?还是我不得不弄乱gtable代码?

Has anyone seen this before and found a workaround or will I have to mess around with the gtable code?

推荐答案

您可以将标签填充到最长字符串的长度,然后以固定宽度的字体显示它们:

You can pad the labels out to the length of the longest string and then display them in a fixed-width font:

max_width = max(nchar(as.character(test$label)))
test$label_padded = sprintf(paste0("%-", max_width, "s"), test$label)

# (Ignore this if not on Windows)
windowsFonts(Consolas = "Consolas")
ggplot(test, aes(x = xdum, y = label_padded, label = data)) + 
    facet_grid(facett~., scales = "free", space = "free") + 
    geom_tile() + 
    theme(axis.ticks = element_blank(), 
          axis.text.y = element_text(hjust = 0, family = "Consolas"))

这篇关于ggplot2:yaxis标签未在各个方面对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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