【问题标题】:Accessing vector of axis ticks for an existing plot in ggplot2访问 ggplot2 中现有绘图的轴刻度向量
【发布时间】:2015-09-22 07:11:20
【问题描述】:

我想在 ggplot 的现有图中获取轴刻度值的向量。我知道 ggplot 对象是一个包含 9 个元素的列表,我想知道是否可以从该列表中提取轴刻度的值。例如,如果我制作这个玩具示例:

library(ggplot2)
g=ggplot(data=mtcars,aes(hp,mpg))+geom_point()

我想要的是向量

 c(100,200,300)
 c(10,15,20,25,30,35)

分别为 x 刻度和 y 刻度 w

有办法解决吗?

非常感谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这些值可以在

    中找到
    ggbld <- ggplot_build(g)
    ggbld$panel$ranges[[1]]$x.major_source
    #[1] 100 200 300
    

    ggbld$panel$ranges[[1]]$y.major_source
    #[1] 10 15 20 25 30 35
    

    它们也可以在这里以字符的形式存储:

    ggbld$panel$ranges[[1]]$x.labels
    #[1] "100" "200" "300"
    ggbld$panel$ranges[[1]]$y.labels
    #[1] "10" "15" "20" "25" "30" "35"
    

    更新:

    以上不适用于 ggplot2_3.0.0,但仍然可以使用以下方法找到该信息:

    ggbld <- ggplot_build(g)
    ggbld$layout$coord$labels(ggbld$layout$panel_params)[[1]]$x.major_source
    ggbld$layout$coord$labels(ggbld$layout$panel_params)[[1]]$x.labels
    

    【讨论】:

    • 哇,感谢您的快速和出色的回应。那么 ggplot_build 函数既会绘制绘图又会返回有关绘图的信息列表?
    • ggplot_build 根据其帮助页面:“...是将绘图规范转换为可以在屏幕上呈现的内容的强大工具。”它不会绘制数据,但会返回有关绘图对象的信息列表。
    • @Jota 显然,ggplot 结构发生了一些变化。要获得面板范围,我必须使用ggplot_build(g)$layout$panel_ranges[[1]]$x.major_source。上述命令返回 NULL。
    • 这不再适用于 ggplot2_3.0.0,有什么想法吗?
    • @zx8754 嗯,也许有更好的方法,但你可以使用ggplot_build(g)$layout$coord$labels(ggplot_build(g)$layout$panel_params)[[1]]$x.major_sourceggplot_build(g)$layout$coord$labels(ggplot_build(g)$layout$panel_params)[[1]]$x.labels
    猜你喜欢
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 2018-05-27
    • 1970-01-01
    • 2012-06-19
    • 2019-11-25
    • 2017-07-21
    相关资源
    最近更新 更多