ggplot: How to retrieve values for axis labels?

后端 未结 2 1787
情歌与酒
情歌与酒 2021-02-15 01:42

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

相关标签:
2条回答
  • 2021-02-15 02:15

    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"
    
    
    0 讨论(0)
  • 2021-02-15 02:16

    Extending on the older post - they can be found with

    ggplot_build(g)$layout$panel_ranges[[1]]$y.labels
    # "20" "30" "40"
    ggplot_build(g)$layout$panel_ranges[[1]]$x.labels
    # "10" "15" "20" "25" "30" "35"
    

    EDIT: works with ggplot2_2.2.1 but not ggplot2 version 3.0.0 - thanks to zx8754 and nilambara for pointing this out

    0 讨论(0)
提交回复
热议问题