r - 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 Numbers
,Part Names
因此图表会更像这样:
解决方案
您需要使用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)
}
推荐阅读
- tensorflow - LSTM 预测结果无法拟合真实值
- java - SAXParser 在 62 元素之后给我一个空值,原因不明,为什么?
- javascript - Rail 6 Webpack 导入 JS 第三方库 Uncaught ReferenceError: x is not defined
- python - 如何修复'消息:无法找到元素:{“method”:“name”,“selector”:“username”}'
- javascript - 选择特定选择选项时如何调用函数?
- java - 如何将下面的代码转换为常规的 java for 循环?
- java - @OneToMany 中的 spring 数据 jpa 过滤子项
- jmeter - 在 JMeter 中启动时出现 UIManager 错误
- angular - Angular 7 Routing 不适用于浏览器后退按钮(哈希更改未加载组件)
- tfs - 我们如何验证 Team Foundation Server 作为我们的开发工具以符合 IEC62304?