[试图弄清楚如何使用别名而不替换R 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
时,图形将更改并聚集两个washer值,如下所示:
我不希望汇总这些值,而只是将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)
}