ggplot2:yaxis标签没有在整个面上对齐

时间:2018-01-31 03:23:44

标签: r ggplot2

我在ggplot中跨轴面对齐轴标签时遇到了一些麻烦。我试图左对齐所有的y轴标签,使文字看起来更均匀,但是" scale = free"参数被添加到脚本中,标签仅在面内对齐。我已经使用一些虚拟代码进行了测试,并出现了同样的问题:

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代码?

1 个答案:

答案 0 :(得分:2)

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

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"))

enter image description here