繁体   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