簡體   English   中英

從圖例中刪除美學 ggplotly R Shiny

[英]Remove an aesthetic from a legend ggplotly R Shiny

我有一個帶有圖表的 shiny 儀表板 - 圖表上的某些條形圖根據相應的選擇器輸入突出顯示,如您在此 gif中所見。

我只希望圖例反映填充,而不是顏色。 我知道如何在 ggplot 中執行此操作,但是如何在ggplotly object 中完成此操作?

我嘗試在 scale_color_manual 中將guide設置為False ,以及設置guide(color = False) ,但沒有運氣。

此外,低優先級,如果有人能給我一個例子,只在整個堆疊條周圍有輪廓,而不是每個單獨的段,那將不勝感激。

可重現的例子:

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)

請注意,不推薦使用guides中縮放 arguments 的邏輯值。 在 ggplot2 中,您將使用guides(color = "none")代替。

在 ggplotly 中,您可以使用style()中的traces參數在圖例中顯示 select 軌跡。

替換ggplotly(dat_selected)

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

要得到

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM