Creating a grouped barplot with two Y axes in R

Hello everyone, I have the following data frame which consists of visual / sightings per hour (SPH) and acoustic / clicks per hour (CPH) data sets for a time span of 8 weeks. I'd like to to have a grouped bar plot which groups the two values for one week together. So e.g. it's 2.676 sightings/h in week 1 and 75.35 clicks/h in week 1. Because of the different units for both variables I also need two y-axes, one for sightings/h on the left and one for clicks/h on the right.

data.frame(Week = c(1, 2, 3, 4, 5, 6, 7, 8), SPH = c(2.676, 2.660, 4.175, 2.134, 
    3.742, 1.395, 4.739, 2.756), CPH = c(75.35, 29.58, 20.51, 80.43, 97.94, 85.39, 168.61, 142.19))

I tried to create a matrix to plot the data, but I don't know how to tell R properly that the first two variables belong to week 1, the second two to week 2 etc.

Hope you guys can help me with this.

Best regards and thanks in advance. :slight_smile:

Here is one method.

library(ggplot2)
library(tidyr)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
DF <- data.frame(Week = c(1, 2, 3, 4, 5, 6, 7, 8), 
           SPH = c(2.676, 2.660, 4.175, 2.134, 3.742, 1.395, 4.739, 2.756), 
           CPH = c(75.35, 29.58, 20.51, 80.43, 97.94, 85.39, 168.61, 142.19))
DFlong <- DF |> pivot_longer(cols = -Week,names_to = "Type") |> 
  mutate(scaled_value=ifelse(Type=="SPH",value,value/10))
head(DFlong)
#> # A tibble: 6 x 4
#>    Week Type  value scaled_value
#>   <dbl> <chr> <dbl>        <dbl>
#> 1     1 SPH    2.68         2.68
#> 2     1 CPH   75.4          7.53
#> 3     2 SPH    2.66         2.66
#> 4     2 CPH   29.6          2.96
#> 5     3 SPH    4.18         4.18
#> 6     3 CPH   20.5          2.05

ggplot(DFlong,aes(x=Week, y = scaled_value,fill= Type)) + 
  geom_col(position="dodge") + 
  scale_y_continuous(sec.axis = sec_axis(~ . * 10, name = "CPH"))+
  labs(y="SPH")

Created on 2022-01-18 by the reprex package (v2.0.1)

R always says "unexpected token '>'" in the pivot command. Do I need to install another package?
It also says "couldn't find objext 'Type'".

But otherwise thanks! :slight_smile:

What version of R are you using?

I'm using R 4.0.3 with the RStudio overlay.

FJCC's code uses the native pipe operator introduced in R 4.1. Change |> to %>% and it should run fine.

Perfect. Thank you. :slight_smile:

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.