使用 ggplot2 以粗体显示各个轴标签

Justify individual axis labels in bold using ggplot2

改编自这个问题和解决方案的问题:

我想根据满足条件有选择地调整水平轴标签。所以借用上面的问答我已经建立了一个例子:

require(ggplot2)
require(dplyr)
set.seed(36)
xx<-data.frame(YEAR=rep(c("X", "Y"), each=20),
           CLONE=rep(c("A", "B", "C", "D", "E"), each=4, 2),
           TREAT=rep(c("T1", "T2", "T3", "C"), 10),
           VALUE=sample(c(1:10), 40, replace=T))

# Simple plot with factors on y axis
ggplot(xx, aes(x = VALUE, y=CLONE, fill=YEAR)) + 
    geom_bar(stat="identity", position="dodge") +
    facet_wrap(~TREAT)

好的,所以我采用了上述问题+答案中的函数来生成理由向量:

# Modify to control justification
colorado2 <- function(src, boulder) {
    if (!is.factor(src)) src <- factor(src)                   
    src_levels <- levels(src)                                 
    brave <- boulder %in% src_levels                         
    if (all(brave)) {                                         
        b_pos <- purrr::map_int(boulder, ~which(.==src_levels)) 
        b_vec <- rep(0.2, length(src_levels))               
        b_vec[b_pos] <- 0.9                                 
        b_vec                                                  
    } else {
        stop("All elements of 'boulder' must be in src")
    }
}

# Redraw the plot with modifcation
ggplot(xx, aes(x = VALUE, y=CLONE, fill=YEAR)) + 
    geom_bar(stat="identity", position="dodge") +
    facet_wrap(~TREAT) +
    theme(axis.text.y=element_text(hjust=colorado2(xx$CLONE, c("A", "B", "E"))))

我遇到了这个不幸的烂摊子:

标签在我想要的方向上是合理的 - 但由于我无法弄清楚的原因占用了太多的情节。我该如何解决这个问题?

您采用的方法是破解底层网格图形引擎,结果可能并不总是很明显。请参阅 以获取进入 grob 树并修复问题的答案。

但是,对于问题中所述的问题,有一个简单的解决方案,不需要任何黑客攻击。只需制作带有一些尾随空格的标签。我在这里手动完成了此操作,但您也可以编写一个函数来执行此操作。

ggplot(xx, aes(x = VALUE, y=CLONE, fill=YEAR)) + 
  geom_bar(stat="identity", position="dodge") +
  scale_y_discrete(breaks = c("A", "B", "C", "D", "E"),
                   labels = c("A    ", "B    ", "C", "D", "E    ")) +
  facet_wrap(~TREAT)

我做了一些挖掘。问题在于 ggplot 如何设置 y 轴 grob 的 grob 宽度。它假定 hjust 在所有标签中都相同。我们可以通过对 grob 树进行一些修改来解决这个问题。以下代码已使用 ggplot2 的开发版本进行测试,可能无法像使用当前发布的版本编写的那样工作。

首先,一个简单的可重现示例:

p <- ggplot(mpg, aes(manufacturer, hwy)) + geom_boxplot() + coord_flip() + 
  theme(axis.text.y = element_text(hjust = c(rep(1, 10), rep(0, 5))))
p # doesn't work

问题是轴 grob 的 grob 宽度被设置为整个绘图区域。但是我们可以手动进去固定宽度。不幸的是,我们必须在多个位置修复它:

# get a vector of the y labels as strings
ylabels <- as.character(unique(mpg$manufacturer))

library(grid)
g <- ggplotGrob(p)

# we need to fix the grob widths at various locations in the grob tree
g$grobs[[3]]$children[[2]]$widths[1] <- max(stringWidth(ylabels))
g$grobs[[3]]$width <- sum(grobWidth(g$grobs[[3]]$children[[1]]), grobWidth(g$grobs[[3]]$children[[2]]))
g$widths[3] <- g$grobs[[3]]$width

# draw the plot
grid.newpage()
grid.draw(g)

ggplot2的轴图代码大概可以像我一开始那样修改计算宽度,然后问题就消失了。