Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extracting guide data #5337

Closed
wants to merge 5 commits into from
Closed

Conversation

teunbrand
Copy link
Collaborator

This PR is the updated version of #5096.
It aims to address issues such as #5004.

Briefly, it adds a guide_data() function to programmatically access values and labels of axes and legends. More motivation is mentioned in #5096 (comment).

Here is what is different relative to the previous PR:

  • This PR uses the new guide system.
  • No kerfuffle with CoordSf, as that coord uses the new guide system now.
  • If there is only 1 matching guide, it outputs a data.frame directly instead of a list.

Examples:

devtools::load_all("~/packages/ggplot2/")
#> ℹ Loading ggplot2

# A typical plot
p <- ggplot(mtcars) +
  aes(mpg, disp, colour = drat, size = drat) +
  geom_point() +
  facet_wrap(vars(cyl), scales = "free_x")

# Getting guide data for position aesthetic in particular panel
guide_data(p, "x", i = 1, j = 2)
#>           x .value .label y
#> 1 0.0959596     18     18 0
#> 2 0.3484848     19     19 0
#> 3 0.6010101     20     20 0
#> 4 0.8535354     21     21 0

# Getting guide data for a legend
guide_data(p, "size")
#>       size .value .label
#> 1 2.662822    3.0    3.0
#> 2 3.919819    3.5    3.5
#> 3 4.779645    4.0    4.0
#> 4 5.477285    4.5    4.5

# If guides are merged, `guide_data()` reports merged guide data
guide_data(p + guides(colour = "legend"), "size")
#>    colour .value .label     size
#> 1 #1A3855    3.0    3.0 2.662822
#> 2 #28557C    3.5    3.5 3.919819
#> 3 #3874A5    4.0    4.0 4.779645
#> 4 #4894D0    4.5    4.5 5.477285

Created on 2023-06-26 with reprex v2.0.2

Comment on lines +282 to +285
if (isTRUE(get_key)) {
return(lapply(guides$params, `[[`, "key"))
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought it was cleaner to early-exit out of guides$build() than to re-implement the build code.

@teunbrand
Copy link
Collaborator Author

teunbrand commented Jul 1, 2023

@cpsievert since {plotly} extracts guide information, and this is the intended use-case for this PR, do you think this PR extracts enough information from guides to be useful?

@cpsievert
Copy link
Contributor

Seems good to me, thanks!

@teunbrand
Copy link
Collaborator Author

Closing this PR in favour of #5506.

@teunbrand teunbrand closed this Nov 3, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants