ggplot:如何获取轴标签的值? [英] ggplot: How to retrieve values for axis labels?

查看:119
本文介绍了ggplot:如何获取轴标签的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何提取下面ggplot中分别用于标记y和x轴的数字(分别为20, 30, 4010 , 15 ,20 ,25, 30, 35)?

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

情节

来自 r-statistics.co

可复制的代码

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

我尝试查看str(g)的输出,但是效果不佳.

I've tried looking through the output of str(g), but with lttle success.

推荐答案

基于CPak的答案,ggplot2_3.0.0的结构略有变化.现在可以使用以下方式提取标签:

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"

ggplot2_3.3.0开始,使用以下标签找到标签:

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"

这篇关于ggplot:如何获取轴标签的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆