繁体   English   中英

R Plotly - 为 x 轴变量使用别名

[英]R Plotly - use alias for x-axis variable

试图弄清楚如何使用别名但不替换 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 Names替换Part Numbers ,这样图形就会更像这样:

最终的

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

有关更多信息,请参阅schema() : object ► layout ► 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)
}

结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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