Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single legend for Plotly subplot for line plots created from two data frames in R

Tags:

r

plotly

I am trying to plot line charts from two data frames where first columns of both data frames are to be plotted in one frame and so forth. And finally all the plots are to be put under one subplot. But I am getting multiple legends with same symbols. The data frames are-

d1 <- data.frame(x = 1:5,
                 y = c(2, 3, 4, 1, 5),
                 z = c(2, 1, 4, 6, 8))

d2 <- data.frame(x = 1:5,
                 y = c(1, 5, 8, 9, 11),
                 z = c(3, 5, 8, 13, 11))

The code I am trying to generate the subplot is-

py <-
  plot_ly(
    x = d1$x,
    y = d1$y,
    type = "scatter",
    mode = "lines",
    name = names(d1)[2],
    line = list(color = "#56B4E9")
  ) %>% add_trace(y = d2$y,
                  name = names(d1)[3],
                  line = list(color = "#D55E00"))

pz <-
  plot_ly(
    x = d1$x,
    y = d1$z,
    type = "scatter",
    mode = "lines",
    name = names(d1)[2],
    line = list(color = "#56B4E9")
  ) %>% add_trace(y = d2$z,
                  name = names(d1)[3],
                  line = list(color = "#D55E00"))

subplot(py, pz)

The output is- enter image description here

Is there any way to get rid of the duplicate legends?

Thanks in advance.

like image 994
Tanvir Khan Avatar asked Apr 26 '26 08:04

Tanvir Khan


1 Answers

This can be achieved by first bringing the data in the right shape which also simplifies the plotting. Simply row bind your dfs e.g. via dplyr::bindrows and you have the variable you need for setting up the legendgroup. Also, your colors don't reflect the variables y and z but the datasets. Try this:

library(dplyr)
library(plotly)

d1 <- data.frame(x = 1:5,
                 y = c(2, 3, 4, 1, 5),
                 z = c(2, 1, 4, 6, 8))

d2 <- data.frame(x = 1:5,
                 y = c(1, 5, 8, 9, 11),
                 z = c(3, 5, 8, 13, 11))

# Bind the dfs
d3 <- bind_rows(list(d1 = d1, d2 = d2), .id = "id")

py <- d3 %>% 
  plot_ly(x = ~x, y = ~y, color = ~id, legendgroup= ~id) %>% 
  add_lines(colors = c("#D55E00", "#56B4E9"))

pz <- d3 %>% 
  plot_ly(x = ~x, y = ~z, color = ~id, legendgroup= ~id) %>% 
  add_lines(colors = c("#D55E00", "#56B4E9"), showlegend = FALSE)

subplot(py, pz) %>% 
  layout(legend=list(title=list(text='<b> Dataset </b>')))

Created on 2020-04-10 by the reprex package (v0.3.0)

enter image description here

like image 113
stefan Avatar answered Apr 29 '26 01:04

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!