使用 Plotly 将图例放在子图中

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

我正在尝试使用 Plotly 制作多面图。下面你可以看到我的代码

library(plotly)

fig1 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(20, 14, 23),
  name = "SF Zoo",
  type = "bar",marker = list(color = '#ff7f0e')
)

fig2 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(50, 24, 3),
  name = "SF Zoo",
  type = "bar",marker = list(color = '#d62728')
)

fig3 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(10, 24, 67),
  name = "SF Zoo",
  type = "bar",marker = list(color = '#9370DB')
)

fig4 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(10, 24, 67),
  name = "SF Zoo",
  type = "bar",marker = list(color = '#2ca02c')
)

这段代码产生了四个地块,现在下一步就是把它们放在一起。

fig<-subplot(
  style(fig1, showlegend = TRUE),
  style(fig2, showlegend = TRUE),
  style(fig3, showlegend = TRUE),
  style(fig4, showlegend = TRUE),
  nrows = 2, margin = 0.05
)
fig

上面代码的输出是下图

你可以看到在右上角,所有图例都在一起,而不是每个图例都有一个图例。

那么谁能帮我解决这个问题,并在每个图形之间添加图例,如下图所示?

r plotly
1个回答
2
投票

而不是使用

subplot
一种选择是将您的地块安排为单独的容器,我使用
div
crosstalk::bscols
为了方便:

library(plotly)
library(htmltools)

legend <- list(orientation = "v", y = 1, x = .85)

fig1 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(20, 14, 23),
  name = "SF Zoo",
  type = "bar", marker = list(color = "#ff7f0e"),
  legendgroup = "1"
) |>
  layout(showlegend = TRUE, legend = legend)

fig2 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(50, 24, 3),
  name = "SF Zoo",
  type = "bar", marker = list(color = "#d62728"),
  legendgroup = "2"
) |>
  layout(showlegend = TRUE, legend = legend)

fig3 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(10, 24, 67),
  name = "SF Zoo",
  type = "bar", marker = list(color = "#9370DB")
) |>
  layout(showlegend = TRUE, legend = legend)

fig4 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(10, 24, 67),
  name = "SF Zoo",
  type = "bar", marker = list(color = "#2ca02c")
) |>
  layout(showlegend = TRUE, legend = legend)

htmltools::div(
  crosstalk::bscols(
    fig1, fig2
  ),
  crosstalk::bscols(
    fig3, fig4
  )
) |>
  htmltools::browsable()

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