Normally the legend of a plotly plot is positioned right to the plot. When added to a box in Shiny its scales well with the legend, no matter how small the box is...however when the legend is placed horizontally, the legend covers the plot when the box is scaled too small. Why is this? And how can I fox this?
Code plot:
x1 <- rnorm(50)
x2 <- rnorm(10)
fig <- plot_ly()
fig <- fig %>%
add_histogram(x = ~x1, name = "X1", marker = list(color = "red")
) %>%
add_histogram(x = ~x2, name = "X2", marker = list(color ="#blue")
) %>%
layout(legend = list(orientation = "h",
traceorder= 'normal',
xanchor = "center",
x = 0.5)
)
Code Shiny app:
ui <- dashboardPage(dashboardHeader(),
dashboardSidebar(),
dashboardBody(
box(
title = "test",
width = 4,
height = "auto",
plotlyOutput("plot1", height = "360px"),
inline = F
)
))
server <- function(input, output, session) {
output$plot1 <- renderPlotly({
fig
})
}
shinyApp(ui, server)
CodePudding user response:
I used a combination of the margin
parameter of plotly
's layout
, and the y
parameter of the legend
to generate the output below.
Code:
library(tidyverse)
library(shiny)
library(shinydashboard)
library(plotly)
x1 <- rnorm(50)
x2 <- rnorm(10)
# THIS CHANGE
m <- list(
l = 10,
r = 10,
b = 100,
t = 10,
pad = 20
)
fig <- plot_ly()
fig <- fig %>%
add_histogram(x = ~x1, name = "X1", marker = list(color = "red")
) %>%
add_histogram(x = ~x2, name = "X2", marker = list(color ="#blue")
) %>%
layout(legend = list(orientation = "h",
traceorder= 'normal',
xanchor = "center",
x = 0.5,
y = -0.3), # THIS CHANGE
margin = m # THIS CHANGE
)
ui <- dashboardPage(dashboardHeader(),
dashboardSidebar(),
dashboardBody(
box(
title = "test",
width = 4,
height = "auto",
plotlyOutput("plot1", height = "360px"),
inline = F
)
))
server <- function(input, output, session) {
output$plot1 <- renderPlotly({
fig
})
}
shinyApp(ui, server)