根据selectInput更改图表图表y变量

use*_*975 15 r shiny plotly

我正在创建一个简单的折线图,可以在Shiny中正确呈现.

我现在添加了一个selectInput,其名称为2个不同的度量,写在我的数据集中.我希望我的y变量能够相应地改变.

p <- plot_ly(data = LineChartData(), x= Calendar.Month, y = input$Measure, type = "line", group = Calendar.Year, col = Calendar.Year)
Run Code Online (Sandbox Code Playgroud)

不幸的是,图表只有一点呈现.它不是在输入$ Measure并在我的数据集中找到该字段.

我知道在使用ggplot时,我会将我的aes切换为aes_string.在情节上是否有类似的解决方案?

编辑:这是一些可重现的代码

这是ui.R文件

    #ui.R

shinyUI(
  fluidPage(
    titlePanel("Inbound Intermediary Performance"),

  sidebarLayout(
    sidebarPanel(
    h4("Parameters"),
    br(),
    selectInput("Measure", "Measure", c("Var1","Var2"))
    ),
    mainPanel(

      plotlyOutput("lineChart")

      )

  )

        )

)
Run Code Online (Sandbox Code Playgroud)

server.R

#server.R
library(plotly)
library(shiny)
library(ggplot2)





#Create data
data <- data.frame(Month = c(1,2,3,4,5,6,7,8,9,10,11,12), Var1 = c(36,33,30,27,24,21,18,15,12,9,6,3), Var2 = c(4,8,12,16,20,24,28,32,36,40,44,48))



shinyServer(function(input, output) {


  #Create plot

  output$lineChart <- renderPlotly({

    #using ggplot
    p <- ggplot(data=data, aes_string(x='Month', y = input$Measure)) +geom_line(size = 1.5) + theme_minimal()
    ggplotly(p)



    #Using PLotly
    #p <- plot_ly(data = data, x= Month, y = input$Measure, type = "line")

  })

})
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我可以使用我的下拉菜单在Var1和Var2之间切换.我的情节相应变化.代码使用ggplot,它是aes_string函数来获取输入.然后使用ggplotly函数将其转换为绘图交互式绘图.

有没有办法我可以用剧情本地做到这一点?

Ole*_*sii 24

使用base :: get()函数:

p <- plot_ly(data = data, x = ~Month, y = ~get(input$Measure), type = "line")
Run Code Online (Sandbox Code Playgroud)

或使用ggplot相同:

p <- ggplot(data = data, aes(x = Month, y = get(input$Measure))) +
geom_line(size = 1.5) + 
theme_minimal()
ggplotly(p)
Run Code Online (Sandbox Code Playgroud)


Mal*_*l_a 1

只需用作data[ ,input$Measure]您的 y 变量:

p <- plot_ly(data = data, x= Month, y = data[ ,input$Measure], type = "line")
Run Code Online (Sandbox Code Playgroud)