anorlondo
anorlondo

Reputation: 397

Remove an aesthetic from a legend ggplotly R Shiny

I have a shiny dashboard with a graph - certain bars on the graph are highlighted based on a corresponding picker input, as you can see in this gif.

I only want the legend to reflect the fill, not the colour. I know how to do this in ggplot, but how can I accomplish this in a ggplotly object?

I've tried setting the guide to False in scale_color_manual, as well as setting guide(color = False), but no luck.

Also, of low priority, if anyone could give me an example of only having the outline around the whole of the stacked bar, not each individual segment, that would be appreciated.

Reproducible example:

library(shiny)
library(shinyWidgets)
library(tidyverse)
library(plotly)

dat <- data.frame(
  location = rep(c("Loc1", "Loc2", "Loc3"), each = 3),
  category = rep(c("cat1", "cat2", "cat3"), 3),
  value = runif(9, 20, 50)
)


ui <- fluidPage(

  
    sidebarLayout(
        sidebarPanel(
            pickerInput(
              inputId = "selected",
              label = "Select a category:",
              choices = c("Loc1", "Loc2", "Loc3")
            )
        ),

 
        mainPanel(
           plotlyOutput("outputPlot")
        )
    )
)


server <- function(input, output) {
  output$outputPlot <- renderPlotly({
    dat_selected <- dat %>%
      # Mutate flag based on selected location
      mutate(selected = ifelse(location == input$selected, 1, 0)) %>%
      ggplot(
        aes(
          x = value,
          y = location,
          group = category,
          fill = category,
          color = as.factor(selected)
        )
      ) + geom_bar(stat = "identity") +
      scale_fill_manual(values = c("yellow", "white", "blue")) +
      scale_color_manual(values = c("white", "red"), guide = "none") +
      guides(color = F)
    
    ggplotly(dat_selected)
  })
    
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 1

Views: 1019

Answers (1)

Martin C. Arnold
Martin C. Arnold

Reputation: 9658

Note that logical values to scale arguments in guides are deprecated. In ggplot2 you would use guides(color = "none") instead.

In ggplotly you may select traces shown in the legend using the traces argument in style():

Replace ggplotly(dat_selected) by

p <- ggplotly(dat_selected) %>%
  style(showlegend = FALSE, traces = c(2, 4, 6))
p

Changing legend entry labels is not straightforward. You may alter labels by modifying list entries in the generated object p:

p <- ggplotly(dat_selected) %>%
  style(showlegend = FALSE, traces = c(2, 4, 6))

p$x$data[[1]]$name <- "cat1"
p$x$data[[3]]$name <- "cat2"
p$x$data[[5]]$name <- "cat3"

p

(Confusingly, indices of the nested lists in p$x$data we need to modify differ from the trace indices above. This is seen from looking at the structure of p at runtime.)

The result looks like this:

enter image description here

Upvotes: 1

Related Questions