从R中的两个数据帧创建的线图的图子子图的单个图例

问题描述 投票:0回答:1

我正在尝试绘制来自两个数据帧的折线图,其中两个数据帧的第一列都将绘制在一个帧中,依此类推。最后,所有地块都将放在一个子图中。但是我得到了多个带有相同符号的图例。数据帧是-

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))

我试图生成子图的代码是-

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)

输出为-enter image description here

有什么方法可以消除重复的图例?

谢谢。

r plotly r-plotly
1个回答
0
投票

这可以通过首先使数据具有正确的形状来实现,这也简化了绘图。只需行绑定您的dfs例如通过dplyr::bindrows,您将拥有设置legendgroup所需的变量。另外,您的颜色不会反映变量y和z,而是反映数据集。试试这个:

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>')))

reprex package(v0.3.0)在2020-04-10创建

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.