How can you extract the numbers used to label the y and x axes in the ggplot below (respectively 20, 30, 40
and 10 , 15 ,20 ,25, 30, 35
)?
Plot
From r-statistics.co
Reproducible code
# Scatterplot
theme_set(theme_bw()) # pre-set the bw theme.
g <- ggplot(mpg, aes(cty, hwy))
g + geom_count(col="tomato3", show.legend=F) +
labs(subtitle="mpg: city vs highway mileage",
y="hwy",
x="cty",
title="Counts Plot")
I've tried looking through the output of str(g)
, but with lttle success.
Building on CPak's answer, the structure has changed slightly for ggplot2_3.0.0
. Labels can now be extracted with:
ggplot_build(g)$layout$panel_params[[1]]$y.labels
#[1] "20" "30" "40"
ggplot_build(g)$layout$panel_params[[1]]$x.labels
#[1] "10" "15" "20" "25" "30" "35"
EDIT:
As of ggplot2_3.3.0
the labels are found using:
# check package version
utils::packageVersion("ggplot2")
y_labs <- ggplot_build(g)$layout$panel_params[[1]]$y$get_labels()
y_labs[!is.na(y_labs)]
#[1] "20" "30" "40"
x_labs <- ggplot_build(g)$layout$panel_params[[1]]$x$get_labels()
x_labs[!is.na(x_labs)]
#[1] "10" "15" "20" "25" "30" "35"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With