用于子图的Plotly legendgroup,因此单个图例控制所有图表

adi*_*aya 9 r shiny plotly

我正在使用plotlyr来生成一些子图.玩具示例如下所示.

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

## Toy Example
ui <- fluidPage(
  h3("Diamonds"),
  plotlyOutput("plot", height = 600)
)

server <- function(input, output, session) {

  # reduce down the dataset to make the example simpler
  dat <- diamonds %>% 
    filter(clarity %in% c("I1", "IF")) %>%
    mutate(clarity = factor(clarity, levels = c("I1", "IF")))

  output$plot <- renderPlotly({

    # Generates the chart for a single clarity
    byClarity <- function(df){

      Clarity <- df$clarity[1];

      plot_ly(df, x = ~carat, y = ~price, color = ~cut, name = ~clarity) %>%
        add_trace(
          type="bar"
          ## Also tried adding this with no success
          # legendgroup = ~cut
        ) %>%
        layout(
          barmode = "stack"
        )
    }

    dat %>% 
      split(.$clarity) %>% 
      lapply(byClarity) %>%
      subplot(nrows = NROW(.), shareX = TRUE, which_layout = "merge")
  })
} 

shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)

我想制作一些传说,点击图例上的"剪切"将显示/隐藏两个图表中的"剪切",而不仅仅是与该图例关联的图表.

DefaultVsIdeal

我查看了legendgroup,但无法弄清楚如何将它与之相关联cut而不是clarity(clarity我正在使用的分组来制作子图).

我还需要解决方案来处理raw plot_ly而不是ggplotly因为plot_ly我需要的其他功能是不可用的ggplotly.

任何帮助,将不胜感激.我使用plotly_4.5.2,dplyr_0.5.0shiny_0.14.

Rom*_*man 1

好的,这是一个使用以下解决方案ggplot2

library(ggplot2)
library(dplyr)
library(plotly)
dat <- diamonds %>% 
  filter(clarity %in% c("I1", "IF")) %>%
  mutate(clarity = factor(clarity, levels = c("I1", "IF")))
# Function for nice labels
k_label <- function(x) {
 c(0, paste0((x)/1000,"K")[-1])
}
# ggplot
p <- ggplot(dat,aes(x=carat, y=price, fill=cut)) + 
           geom_bar(stat="identity") + 
           facet_wrap(~clarity,nrow=2, scales = "free_y") +
           scale_y_continuous(labels = k_label) + 
           theme_minimal() + ylab("") + xlab("") +
           theme(legend.title=element_blank(),
                 panel.grid.major.x=element_blank())
# a plotly
ggplotly(p)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述