Justify individual axis labels in bold using ggplot2

◇◆丶佛笑我妖孽 提交于 2019-12-05 06:30:07

I did some digging. The problem is with how ggplot sets the grob width of the y axis grob. It assumes that hjust is the same across all labels. We can fix this with some hacking of the grob tree. The following code was tested with the development version of ggplot2 and may not work as written with the currently released version.

First, a simple reproducible example:

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

The problem is that the grob width of the axis grob gets set to the entire plot area. But we can manually go in and fix the width. Unfortunately we have to fix it in multiple locations:

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

The axis-drawing code of ggplot2 could probably be modified to calculate width like I did here from the outset, and then the problem would disappear.

The method you employ is hacking the underlying grid graphics engine and results may not always be obvious. See here for an answer that goes into the grob tree and fixes things.

However, for the problem as stated in the question, there is a simple solution that doesn't require any hacking. Just make labels that have some trailing spaces. I did this manually here, but you could also write a function that does this.

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!