larry77
larry77

Reputation: 1533

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

Please have a look at the reprex at the end of the post. Essentially, I create a very simple ggplot2 visualization inside shiny. When I call ggplotly on it in order to get a plotly interactive visualization, the plot legend which was at the top of the plot, gets shifted to the right. Any idea about how to fix that?

Many thanks!

library(shiny)
library(plotly)
library(ggplot2)
library(dplyr)


df <- tibble(x=seq(20), y=seq(20), type=c(rep("a", 10), rep("b", 10)))


ui <- fluidPage(

mainPanel(
    plotOutput("myplot" ),
    plotlyOutput("myplot2" )
    
    )
    
)



server <- function(input, output) {

myplot <- reactive({
    
gpl1 <- df%>%
    ggplot(aes(x = x, y = y, fill=type)) +
    geom_col()+
    theme(legend.position="top")+
    xlab("x")+
    ylab("y")+
    labs(title = NULL)

gpl1



})



myplot2 <- reactive({
    
gpl2 <- df%>%
    ggplot(aes(x = x, y = y, fill=type)) +
    geom_col()+
    theme(legend.position="top")+
    xlab("x")+
    ylab("y")+
    labs(title = NULL)

ggplotly(gpl2)




})

    
    output$myplot <- renderPlot({
        myplot()
        
    })

    output$myplot2 <- renderPlotly({
        myplot2()
        
    })

    
    
}




shinyApp(ui = ui, server = server)
#> PhantomJS not found. You can install it with webshot::install_phantomjs(). If it is installed, please make sure the phantomjs executable can be found via the PATH variable.
Shiny applications not supported in static R Markdown documents

Created on 2021-09-23 by the reprex package (v2.0.1)

Upvotes: 1

Views: 1579

Answers (1)

lz100
lz100

Reputation: 7360

We can add some plotly grammar to fix it.

layout(legend = list(orientation = 'h', x = 0.45, y = 1.1))

library(shiny)
library(plotly)
library(ggplot2)
library(dplyr)
df <- tibble(x=seq(20), y=seq(20), type=c(rep("a", 10), rep("b", 10)))

ui <- fluidPage(
  mainPanel(
    plotOutput("myplot" ),
    plotlyOutput("myplot2" )
  )
)

server <- function(input, output) {
  myplot <- reactive({
    gpl1 <- df%>%
      ggplot(aes(x = x, y = y, fill=type)) +
      geom_col()+
      theme(legend.position="top")+
      xlab("x")+
      ylab("y")+
      labs(title = NULL)
    gpl1
  })
  
  myplot2 <- reactive({
    gpl2 <- df%>%
      ggplot(aes(x = x, y = y, fill=type)) +
      geom_col()+
      theme(legend.position="top")+
      xlab("x")+
      ylab("y")+
      labs(title = NULL)
    ggplotly(gpl2) %>% 
      layout(legend = list(orientation = 'h', x = 0.45, y = 1.1))
  })
  output$myplot <- renderPlot({
    myplot()
  })
  output$myplot2 <- renderPlotly({
    myplot2()
  })
}
  
shinyApp(ui = ui, server = server)

enter image description here

Upvotes: 1

Related Questions