davidcarslaw / openair

Tools for air quality data analysis
https://davidcarslaw.github.io/openair/
GNU General Public License v2.0
304 stars 113 forks source link

`polarPlot()` should return some information regarding it's y axis scale (esp. for negatives) #376

Open jack-davison opened 8 months ago

jack-davison commented 8 months ago

Feature request

Hi @davidcarslaw - this is a bit of a "programming with openair"-type feature request, after conversations with @mooibroekd.

At the min, polarPlot() returns cartesian coordinates which can, if the user wishes, be converted into polar coordinates to plot on a true radial axis - e.g., in the in-development ggopenair:

https://github.com/jack-davison/ggopenair/blob/47bf958a6149bdb6ed3a198da6c9b1e82fea723c/R/polar_plot.R#L638-L647

This is fine if the y-axis starts at 0 - as it does for wind speed - but for more esoteric x values that can go into the negatives, a simple cartesian transformation won't do:

dat <- openair::mydata
dat$newvar <- dat$ws - (max(dat$ws, na.rm = TRUE) / 2)

openair::polarPlot(dat, "nox", x = "newvar")


ggopenair::polar_plot(dat, "nox", x = "newvar") +
  ggopenair::scale_opencolors_c() +
  ggopenair::theme_polar()

Created on 2024-01-29 with reprex v2.0.2

What would the best way be to extract the y-scale from the polarPlot() function? Could we return it as an attribute or part of the {openair} object?

mooibroekd commented 3 months ago

Hi @jack-davison,

Perhaps we don't need to have changes to the openair functions. In your example newvar is plotted at the radial axis. We already know the statistics of newvar as it is in the data:

dat <- openair::mydata
dat$newvar <- dat$ws - (max(dat$ws, na.rm = TRUE) / 2)

range(dat$newvar, na.rm = TRUE)
#> [1] -10.08  10.08

# the same info provided as attribute by polarplot:
polar_data <- openair::polarPlot(dat, "nox", x = "newvar", plot = FALSE)

attributes(polar_data$data)$radial_scale
#> [1] -10.08  10.08

Without access to the data it is a bit difficult, but I am assuming that the radial_scale calculated in the ggopenair function is [0 - 20.16]. My proposal would be the following: subtract (20.16+0)/2 from the radial_scale for ggplot. That sets it in the [-10.08 - 10.08] range. With this example it is now set in the correct range. However, this is only because the center of the radial_scale for newvar is 0 (10.08 + -10.08). The correct scale for ggplot would be to add the center of the newvar (in this case 0).

It should be noted that the center of the range for the variable is not always 0, so there might be a positive or negative offset.

I think that this updated scale can be used of the breaks and labels on the radial axis. Would love to hear your comment on this solution.