首页 > 解决方案 > R Plotly - 为 x 轴变量使用别名

问题描述

试图弄清楚如何使用别名但不替换 R Plotly 条形图 x 轴中的变量。举个例子:

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)
}

运行时,它会输出如下图:

数字

当您单击单选按钮将其更改为 时Name,图表会更改并聚合两个垫圈值,如下所示:

姓名

我不希望这些值聚合,而是简单地将 替换为Part NumbersPart Names因此图表会更像这样:

最终的

标签: rplotlyr-plotly

解决方案


您需要使用ticktext来更改刻度标签,x 需要保持不变。

有关详细信息,请参阅schema():对象 ► 布局 ► layoutAttributes ► xaxis ► ticktext

请检查以下内容:

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)
}

结果


推荐阅读