'How to split legend of a plotly chart when using to two y axes

I am creating a grouped bar plot using plotly. As level of my values differ I am using two y axes. I would like to split a legend (idea presented on a picture below) to make it easier to link variables with corresponding axes. Is there any way to do it in plotly?

library(plotly)
library(dplyr)

Year <- c(2019, 2020, 2021)
var1 <- c(200, 140, 230)
var2 <- c(1.2, 0.9, 3.1)
data <- data.frame(Year, var1, var2)


plot <- plot_ly() %>% 
    add_bars(data, x = ~Year, y = ~var1, name = 'var1', offsetgroup = 1) %>%
    add_bars(data, x = ~Year, y = ~var2, name = 'var2', yaxis = "y2", offsetgroup = 2) %>%
    layout(
        yaxis = list(title = ""),
        yaxis2 = list(
        overlaying = "y",
        side = "right"
    ),
    margin = list(b = 100),
    barmode = 'group')

plot

enter image description here



Sources

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

Source: Stack Overflow

Solution Source