简体   繁体   中英

How to change the position of y axis label to be directly on top of the y axis?

I am having trouble placing the y-axis label directly above the y-axis.

I've tried using the margins argument to guide the label. I get the right and left adjustment correctly adjusted, but I cant get the label further to the top of the graph specifying the argument t = xx in the margins.

The code produces the graph below. As you can see the y-axis-label need to be adjusted further upwards b/c I want it to be directly on top of the y-axis.

Cheers,

图形


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

You could pretend like it's just any old text and place it wherever you like.

Fiddle with hjust , vjust , ymin or xmin to get the label exactly where you want it.

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM