下午好,
我正在尝试从ggplot2的经济学数据集中绘制一个简单的时间序列。该应用会加载,然后显示具有正确轴的图表,但不包含任何绘图数据。任何帮助将不胜感激。最好,乔
library(shiny)
library(plotly)
library(tidyverse)
df <- economics
datalst = colnames(df)
ui <- pageWithSidebar(
headerPanel("test"),
sidebarPanel(
selectInput(inputId = "x",
label = "Choose the x axis",
datalst),
selectInput(inputId = "y",
label = "Choose the y axis",
datalst, datalst[[2]])
),
mainPanel(
plotlyOutput("plot")
)
)
server <- function(input, output) {
dataset <- reactive({
df[, c(input$x, input$y)]
})
output$plot = renderPlotly({
plot_ly(dataset(), x = ~input$x, y = ~input$y,type = 'scatter', mode = 'lines')
})
}
shinyApp(ui = ui, server = server)
这里的技巧是避免非标准评估,因为input$x
和input$y
评估为字符串,而plotly
在示例中使用as则需要〜后面的裸列名称。您可以使用以下方法解决此问题:
server <- function(input, output) {
dataset <- reactive({
df[, c(input$x, input$y)]
})
output$plot = renderPlotly({
plot_ly(x = dataset()[[input$x]], y = dataset()[[input$y]],type = 'scatter', mode = 'lines')
})
}
进一步的改进可以是将反应性“拆分”为两个,从而使绘图的输入无效,并且仅当相应的输入更改时才重新计算:
server <- function(input, output) {
dataset_x <- reactive({
df[, input$x]
})
dataset_y <- reactive({
df[, input$y]
})
output$plot = renderPlotly({
plot_ly(x = dataset_x()[[1]], y = dataset_y()[[1]], type = 'scatter', mode = 'lines')
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句