簡體   English   中英

如何將反應性 x 和 y 軸標簽添加到 shiny plotly 圖表?

[英]how to add reactive x and y axis labels to shiny plotly graph?

我正在努力尋找一種方法來為這個 plotly 圖表添加軸標簽。 因為它與我在應用程序之外使用 plotly 甚至 ggplot 時有點不同,所以我似乎無法讓它工作。 有小費嗎?

我需要 x 和 y 軸標簽隨代碼右側的小部件一起更改。 我也不確定標簽是否已經顯示,以及圖表太大而無法顯示的問題。

library(shiny)
library(plotly)
library(tibble)
library(tidyverse)
library(tidyr)
library(readr)
library(dplyr)
library(ggplot2)
library(gapminder)


#read data
gm <- gapminder


# Define UI ----
ui <- fluidPage(
  column(3,offset = 4, titlePanel("Explore Gapminder Data with Shiny")),
  headerPanel('Graphs'),
  mainPanel(
    plotlyOutput('plot')
  ),
  sidebarPanel(
    #variable selection for x-axis
    selectInput(inputId ='xvrbl', #The input slot that will be used to access the value.
                label = 'X-Axis Variable', #Display label for the control, or NULL for no label.
                choices = colnames(gm), #List of values to select from
                selected = 'CO2 emissions (metric tons per capita)'
    ),
    
    checkboxInput(inputId = "LogX", 
                  label = "Log Transform", 
                  value = FALSE),
    
    #variable selection for y-axis
    selectInput(inputId ='yvrbl', #The input slot that will be used to access the value.
                label = 'Y-Axis Variable', #Display label for the control, or NULL for no label.
                choices = colnames(gm), #List of values to select from
                selected = 'gdpPercap'
    ),
    
    checkboxInput(inputId = "LogY", 
                  label = "Log Transform", 
                  value = FALSE),
    
    # date range - slider
    sliderInput(
      inputId = "time",
      label = "Years",
      min = min(gm$year),
      max = max(gm$year),
      step = 5,
      value = range(gm$year)
    )
  )
)

server <- function(input, output) {
  x <- reactive({
    x <- dat()[[input$xvrbl]]
    if (input$LogX) x <- log(x)
    return(x)
  })
  
  y <- reactive({
    y <- dat()[[input$yvrbl]]
    if (input$LogY) y <- log(y)
    return(y)
  })
  
  dat <- reactive({
    subset(gm, year >= input$time[[1]], year <= input$time[[2]])
  })
  
  output$plot <- renderPlotly({
    plot_ly(
      x = x(),
      y = y(),
      type = "scatter",
      mode = "markers",
      color = dat()$continent
    )
  })  
}

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

您應該將layout參數指定給renderPlotly

output$plot <- renderPlotly({
    plot_ly(
      x = ~x(),
      y = ~y(),
      type = "scatter",
      mode = "markers",
      color = dat()$continent) %>%
      layout(
      yaxis = list(title = input$yvrbl),
      xaxis = list(title = input$xvrbl)
      )
    
  })  

暫無
暫無

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

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