我正在尝试绘制来自两个数据帧的折线图,其中两个数据帧的第一列都将绘制在一个帧中,依此类推。最后,所有地块都将放在一个子图中。但是我得到了多个带有相同符号的图例。数据帧是-
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)
有什么方法可以消除重复的图例?
谢谢。
这可以通过首先使数据具有正确的形状来实现,这也简化了绘图。只需行绑定您的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创建