use*_*193 6 r axes labels ggplot2
问题和解决方案改编的问题:使用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)
Run Code Online (Sandbox Code Playgroud)
好的,所以我从上面的问题+答案中采用了函数来生成一个理由的向量:
# 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"))))
Run Code Online (Sandbox Code Playgroud)
这些标签在我想要的方向上是合理的 - 但由于我无法弄清楚的原因而占据太多的情节.我该如何解决 ?
我做了一些挖掘。问题在于 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
Run Code Online (Sandbox Code Playgroud)
问题在于轴 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)
Run Code Online (Sandbox Code Playgroud)
ggplot2 的轴绘制代码可能会被修改为计算宽度,就像我从一开始就在这里所做的那样,然后问题就会消失。
| 归档时间: |
|
| 查看次数: |
339 次 |
| 最近记录: |