r - 根据 selectInput 更改绘图图表 y 变量

标签 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)

不幸的是,图表仅呈现一个点。它不会获取 input$Measure 并在我的数据集中查找该字段。

我知道在使用 ggplot 时,我会将 aes 切换为 aes_string。 plotly 中有类似的解决方案吗?

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

这是 ui.R 文件

    #ui.R

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

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

      plotlyOutput("lineChart")

      )

  )

        )

)

服务器.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")

  })

})

在上面的示例中,我可以使用下拉菜单在 Var1 和 Var2 之间切换。我的 plotly 也随之改变。该代码使用 ggplot 及其 aes_string 函数来获取输入。然后使用 ggplotly 函数将其转换为交互式绘图。

有没有办法可以用plotly 本地完成此操作?

最佳答案

使用base::get()函数:

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

或使用 ggplot 进行相同操作:

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

关于r - 根据 selectInput 更改绘图图表 y 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36980999/

相关文章:

python - Plotly subplots - 其 plotly 旁边的图例项

r - 如何在不多次执行的情况下呈现同一分析的多个输出? ( Shiny 的)

r - 在 R 中的一个空间拆分一个因子

r - R Shiny 应用程序中的传单 map 图例不显示颜色

r - 在 Shiny 的文档中显示 ggvis 绘图

R 绘制如何将文本链接到气泡以便在单击图例时将其删除

javascript - 在 Plotly.js 的多个子图中共享痕迹

r - 无法从 R 数据帧中删除空 `character(0)` 或 `list()` 值

r - 自从更新 sp 包后,我通过调用 sp::CRS 定义收到警告

r - sliderinput 中的颜色刻度线和刻度线标签 - Shiny