我无法将y轴标签直接放在y轴上方。
我尝试使用margins参数引导标签。我可以正确调整左右调整,但无法在标签顶部指定标签t = xx的位置到标签的顶部。
代码产生下图。如您所见,y轴标签需要进一步向上调整b / c,我希望它直接位于y轴顶部。
干杯
library(tidyverse)
housing <- txhousing %>% group_by(year, city) %>%
summarise(total = sum(volume, na.rm = T)) %>% filter(city %in% c("El Paso","Dallas", "Houston"))
dat <- housing
yvar <- dat$total
xvar <- dat$year
gruppe <- dat$city
ggplot(data = dat, aes(x = xvar, y = yvar/1e6, colour = gruppe)) + geom_line() + theme_classic() + theme(plot.margin = margin(20,0,0,0), axis.title.y = element_text(angle = 0, margin = margin(t = -20, l = 10, r = -40))) + labs(y = "y-label")
答案 0 :(得分:1)
您可以假装它只是任何旧文本,然后将其放置在任意位置。
对hjust
,vjust
,ymin
或xmin
进行修饰,以将标签精确地放置在所需位置。
library(tidyverse)
library(ggplot2)
library(grid) #grobs come from grid
housing <- txhousing %>% group_by(year, city) %>%
summarise(total = sum(volume, na.rm = T)) %>% filter(city %in% c("El Paso","Dallas", "Houston"))
dat <- housing
yvar <- dat$total
xvar <- dat$year
gruppe <- dat$city
p<-ggplot(data = dat, aes(x = xvar, y = yvar/1e6, colour = gruppe)) +
geom_line() + theme_classic() +
theme(plot.margin = margin(50,0,0,0))+
annotation_custom(
grob = textGrob(label = "y-label", hjust = 0, vjust=-0.9,gp = gpar(cex = 1.0)),
ymin = (max(yvar/1e6)),
xmin = min(xvar)-(0.009*min(xvar)))+
labs(y = NULL)
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off" #this lets you put stuff outside the margins
grid.draw(gt)