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

Tanvir Khan

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.

stefan

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

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

R Plotly Two Plots side by side

В R plotly subplot graph, как показать только одну легенду?

R-plotly: Subplot показывает только нижний график

Регулировка высоты и ширины Plotly :: subplot в R Shiny

Заголовки аннотаций plotly :: subplot исчезают в R Shiny

R ggvis multiple plots from single data frame

How to add two plots to a subplot?

Plotly Legend Item Names in Subplot Graph with Loop

setdiff two single column data frames

R: Conditional replacement using two data frames

Conditional selection two data-frames R

Multiple scatter plots in a single figure from multiple data frame in R using ggplot?

plotly cumulative animation does not work for subplot in R

Отображение всех заголовков сюжета в plotly :: subplot

How to hide legend selectively in a plotly line plot?

Python plotly - add horizontal line to legend

R – How to join two data frames by nearest time-date?

Changing values between two data.frames in R

Combine two data frames in R without repeated entries

Merging two data frames and keeping the extra rows from first df

Pairwise comparisons across columns from two different data frames

Compare values from two pandas data frames, order-independent

How to dynamically add plots (lines/traces) from different sources/datasets to a plotly object in R (Shiny)?

R - creating a complete data frame by combining from other data frames

R + shiny + plotly: ggplotly moves the legend to the right

Привяжите r data.frames, которые содержат столбцы вложенных data.frames

R: разделение data.frames на заданное количество небольших data.frames

Чередование двух data.frames из data.frames в R

Привяжите r data.frames, которые содержат столбцы вложенных data.frames

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    Flutter: Unhandled Exception: FileSystemException: Creation failed, path = 'Directory: '' (OS Error: Read-only file system, errno = 30)

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Bogue étrange datetime.utcnow()

  5. 5

    Как изменить значок приложения для проекта libgdx android

  6. 6

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  7. 7

    Как получить список индексов всех значений NaN в массиве numpy?

  8. 8

    Не удается запустить компилятор cl

  9. 9

    Почему actionPerformed выполняется двумя потоками?

  10. 10

    Дженерики и потоки Java

  11. 11

    How to convert C++/CLI string to const char*

  12. 12

    Запрос Google Таблиц по дате и сгруппировать отсутствующие данные

  13. 13

    Airflow не распознает мои настройки подключения S3

  14. 14

    numpy: в true_divide обнаружено недопустимое значение

  15. 15

    Редактировать существующий файл Excel C # npoi

  16. 16

    Динамическое создание точек / квадратов внутри Picturebox

  17. 17

    discord.py: on_message (message) не работает несколько дней

  18. 18

    TypeError: ownKeys на прокси: результат ловушки не включал аргументы

  19. 19

    Невозможно подключиться к базе данных pgsql с помощью Java REST-API на локальном сервере Tomcat. Стек содержит ExceptionInInitializerError и IllegalStateException

  20. 20

    Passing Core Data objects from UITableViewCell to another View Controller

  21. 21

    Как отфильтровать несколько столбцов в Qtableview?

популярныйтег

файл