eliocamp / metR

Tools for Easier Analysis of Meteorological Fields
https://eliocamp.github.io/metR/
143 stars 22 forks source link

The significant digits issue of legend in the wind vector chart. #161

Closed PanfengZhang closed 1 year ago

PanfengZhang commented 2 years ago

The wind speed magnitude in the legend retains a lot of numbers after the decimal point.

As shown in the following figure, the wind speed in the legend is 26.81044 m/s. This is not very necessary. I just want to show as 27m/s.

rm(list = ls())
library(sf)
library(rnaturalearth)
library(stars)
library(metR)
library(ggplot2)
library(units)
wld <- ne_coastline(returnclass = "sf")
# u wind: https://downloads.psl.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/pressure/uwnd.2022.nc
# v wind: https://downloads.psl.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/pressure/vwnd.2022.nc
diriu <- "C:/documents/rdata/dataset/uwnd.2022.nc"
diriv <- "C:/documents/rdata/dataset/vwnd.2022.nc"
du <- read_ncdf(diriu, var = "uwnd") |> units::drop_units()
dv <- read_ncdf(diriv, var = "vwnd") |> units::drop_units()
u <- du[,,,3, 118] |> as.data.frame()
v <- dv[,,,3, 118] |> as.data.frame()
ds <- merge(u, v, sort = FALSE)
ds[ds$lon > 180, "lon"] <- ds[ds$lon > 180, "lon"] - 360 # 0°-360°转为-180~180°
sf_use_s2(FALSE)
ggplot() +
  geom_sf(data = wld, colour = "blue", size = 0.3) +
  coord_sf(crs = 4326, expand = FALSE) +
  geom_vector(data = ds, aes(x = lon, y = lat, dx = uwnd, dy = vwnd),
              arrow.type = "open", size = 0.3, skip = 4) +
  scale_mag(name = NULL, max_size = 1,
            guide = guide_vector(title = "m/s", title.position = "right")) +
  scale_x_continuous(breaks = seq(-135, 135, 45)) +
  scale_y_continuous(breaks = seq(-45, 45, 45)) +
  ggtitle(paste(ds$time[1], "global wind vector at the 850hPa")) +
  theme_bw() +
  theme(legend.position = c(0.83, 1.08),
        axis.title = element_blank())

2022-04-28global_wind_vector_850hPa Is there any way to solve it?

I know a method, as shown below.

scale_mag(name = "27m/s")

But this method is only suitable for drawing a single wind vector map, and it is not applicable when drawing in batches.

eliocamp commented 2 years ago

scale_mag(..., label = scales::number_format()) should work. Perhaps I should use some kind of "smart" algorithm to select a "nice" number, though.

PanfengZhang commented 2 years ago

Thanks. It solved my issue.