简体   繁体   中英

R Plotly - use alias for x-axis variable

Trying to figure out how to use an alias but not replace the variable in the x-axis of a R Plotly bar graph. Take the following example:

if (interactive()) {
  library(plotly)

  PartNum <- c("123", "456", "789", "321", "654")
  PartName <- c("washer", "nut", "bolt", "washer", "screw")
  PartCount <- c(10, 15, 6, 8, 2)
  data <- data.frame(PartNum, PartName, PartCount)

  ui <- fluidPage(
    radioButtons("radio_PartNumName", "Show Part:",
                 c("Number" = "PartNum", "Name" = "PartName"),
                 inline = TRUE
    ),
    plotlyOutput("partPlot")
  )

  server <- function(input, output, session) {
    output$partPlot <- renderPlotly({
      plot_ly(data,
              x = ~get(input$radio_PartNumName),
              y = ~PartCount,
              type = "bar",
              text = ~PartCount)
    })
  }
  shinyApp(ui, server)
}

When run, it outputs a graph like this:

数字

When you click the radio button to change it to Name , the graph changes and aggregates two washer values like this:

姓名

I'm not wanting the values to aggregate, but instead simply replace the Part Numbers with the Part Names so the graph would like something more like this:

最终的

You'll need to use ticktext to change the tick labels, x needs to be constant.

For further information please see schema() : object ► layout ► layoutAttributes ► xaxis ► ticktext

Please check the following:

library(shiny)
library(plotly)

if (interactive()) {

  PartNum <- c("123", "456", "789", "321", "654")
  PartName <- c("washer", "nut", "bolt", "washer", "screw")
  PartCount <- c(10, 15, 6, 8, 2)
  data <- data.frame(PartNum, PartName, PartCount)

  ui <- fluidPage(
    radioButtons("radio_PartNumName", "Show Part:",
                 c("Number" = "PartNum", "Name" = "PartName"),
                 inline = TRUE
    ),
    plotlyOutput("partPlot")
  )

  server <- function(input, output, session) {
    output$partPlot <- renderPlotly({
      plot_ly(data,
              x = ~PartNum,
              y = ~PartCount,
              type = "bar",
              text = ~PartCount) %>%
      layout(xaxis = list(
        tickmode = "array",
        tickvals = ~PartNum,
        ticktext = ~get(input$radio_PartNumName))
      )
    })
  }
  shinyApp(ui, server)
}

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM