防止更新剧情元素

时间:2016-05-16 21:43:16

标签: r shiny plotly

无论实际显示哪个点,我都试图保持我的绘图的颜色比例和大小比例不变。

ggplot中,我可以使用scale_color_gradient(limits=c(0,1))等参数设置这些常量。但是,我在plot_ly中找不到并行函数,而出于其他原因,我不能在这里使用ggplotly()

我相信这也可以用eventReactive()完成,但我无法理解如何使用它。

这是一个最小的例子,其中图的颜色和大小不断变化。

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

df <- as.data.frame(list("UserID"=c(1,1,1,1,2,2,2,2), 
                          "Category"=c('A','A','B','B','A','A','B','B'),
                          "Rate"=c(2,3,5,6,8,6,7,1),
                          "x"=c(1,3,5,7,2,4,6,8),
                          "y"=c(1,3,5,7,2,4,6,8)
                    ))

ui <- (fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("userInput","Select User", sort(unique(df$UserID)),
                  selected=1),
      checkboxGroupInput("CategoryInput", "Select Category", sort(unique(df$Category)),
                         selected=c('A','B'))
    ),

    mainPanel(
      plotlyOutput("mainPlot")#,
    )
  )
))

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

  # filter for both user and category
  filteredFull <- reactive({
      df %>% 
        filter(
          UserID == input$userInput,
          Category %in% input$CategoryInput
        )
  })

  output$mainPlot <- renderPlotly({
        plot_ly(data=filteredFull(), x=x, y=y,
                       color=Rate, size=Rate,
                       mode='markers')
  })
}

shinyApp(ui, server)

是否可以仅更新显示哪些点,而无需更新颜色/尺寸的比例/范围?

1 个答案:

答案 0 :(得分:5)

Plotly也有这些色阶限制。它们嵌套在marker属性下。您可以设置颜色标度最大值和最小值(数值),使标尺保持不变,无论实际显示哪些点。

我刚刚将marker = list(cmin = 1, cmax = 8)添加到plot_ly命令中。因此,您必须扫描df以确定最大值和最小值。

以下代码:

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

df <- as.data.frame(list(
  "UserID" = c(1, 1, 1, 1, 2, 2, 2, 2), 
  "Category" = c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
  "Rate" = c(2, 3, 5, 6, 8, 6, 7, 1),
  "x" = c(1, 3, 5, 7, 2, 4, 6, 8),
  "y" = c(1, 3, 5, 7, 2, 4, 6, 8)
))

ui <- (fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("userInput","Select User", sort(unique(df$UserID)), selected=1),
      checkboxGroupInput("CategoryInput", "Select Category", sort(unique(df$Category)), selected=c('A','B'))
    ),

    mainPanel(
      plotlyOutput("mainPlot"),
      plotlyOutput("mainPlotFixedSize")
    )
  )
))

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

  # filter for both user and category
  filteredFull <- reactive({
      df %>% 
        filter(
          UserID == input$userInput,
          Category %in% input$CategoryInput
        )
  })

  output$mainPlot <- renderPlotly({
    plot_ly(data=filteredFull(), x=x, y=y,
      color=Rate, size=Rate,
      mode='markers', marker = list(cmin = 1, cmax = 8))
  })

  output$mainPlotFixedSize <- renderPlotly({
    plot_ly(data=filteredFull(), x=x, y=y,
      color=Rate, mode='markers', 
      marker = list(sizemode = "area", size = Rate*3400, cmin = 1, cmax = 8))
  }) 
}

shinyApp(ui, server)