'How do I create two boxplots with a y axis on the left, and a y axis of different scaling on the right? Preferably base R

After much data manipulation, I have the tibble containing all the numbers I need to create two box plots:

head(final)

# A tibble: 6 x 2
  `Maximum Daily Precipitation` `Annual Average Precipitation`
                          <dbl>                          <dbl>
1                          159.                          1426.
2                          170.                          1556.
3                          151.                          1367.
4                          196.                          1469.
5                          150.                          1412.
6                          131.                          1204.

When I make a boxplot of both, I have the following:

boxplot(final,ylab="Precipitation")

boxplot result

Now while the data is correct, I was hoping to present it better by setting two y axes with different scales on the left and on the right. Im looking to set the y axis on the left to go from 0 to 200, and the y axis on the right to go from 0 to 2100.

Im new to R and would like to know if this is possible using Base R? If not, using ggplot2.

Thank you.



Solution 1:[1]

If you want to use ggplot2 this is one way to do it:

library(tidyverse)
df <- structure(list(maxd_prec = c(159, 170, 151, 196, 150, 131),
                     aavg_prec = c(1426, 1556, 1367, 1469, 1412, 1204)),
                class = c("tbl_df", "tbl", "data.frame"),
                row.names = c(NA, -6L))

df %>% 
  pivot_longer(cols = maxd_prec:aavg_prec, names_to = "prec_type", values_to = "prec") %>% 
  mutate(labels = ifelse(prec_type == "aavg_prec", "Annual Average Precipitation", "Maximum Daily Precipitation")) %>% 
  select(-prec_type) %>% 
  ggplot(aes(x = labels, y = prec)) +
  geom_boxplot() +
  facet_wrap(~labels, scales = "free") +
  labs(x = NULL, y = "Precipitation")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 philiptomk