如何在下面的ggplot中提取用于标记y轴和x轴的数字(分别20, 30, 40和10 , 15 ,20 ,25, 30, 35)?
情节
可重现的代码
# 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")
Run Code Online (Sandbox Code Playgroud)
我已经尝试查看输出str(g),但是成功了.
基于 CPak 的回答,ggplot2_3.0.0. 现在可以使用以下方法提取标签:
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"
Run Code Online (Sandbox Code Playgroud)
编辑:从ggplot2_3.3.0标签中找到使用:
# 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"
Run Code Online (Sandbox Code Playgroud)