sometimes_sci
sometimes_sci

Reputation: 199

ggplot2 retrieve y axis title for subtitle

ggplot2 titles the y-axis with the name of the y variable. e.g., the y-axis has "mpg" as the title in the example below:

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point()

Is there a way to use that string value for the subtitle? Obviously I can pass a new string like so:

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  labs(subtitle = "mpg")

But what I want is a way to point to the string value of the y-axis title. For example, I thought this would work:

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  labs(subtitle = axis.title.y, y = "")

Error in dots_list(..., title = title, subtitle = subtitle, caption = caption, : object 'axis.title.y' not found

Ultimately I want to remove the y-axis title and use the subtitle to provide the same info, without having to specify the subtitle string each time (just as I don't have to specify the y-axis title string by default).

Thanks for any tips or advice.

Upvotes: 0

Views: 668

Answers (1)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

Is this the right direction?

p <- ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point()

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  labs(subtitle = p$labels$y, y = "")

Or

ggplot(mtcars, aes(x = disp, y = mpg)) +
  geom_point() +
  labs(subtitle = (ggplot(data=mtcars, aes(x = disp, y = mpg)))$labels$y, y = "")

enter image description here

Upvotes: 2

Related Questions