根据selectInput更改可绘制图表y变量 [英] Change plotly chart y variable based on selectInput
问题描述
我正在创建一个简单的折线图,可以在Shiny中正确显示.
I'm creating a simple line chart which renders correctly in Shiny.
我现在添加了带有两个不同量度名称的selectInput,它们的写法与它们在我的数据集中出现的方式相同.我希望我的y变量相应地更改.
I've now added a selectInput with the names of 2 different measures, written as they appear in my data set. I'd like my y variable to change accordingly.
p <- plot_ly(data = LineChartData(), x= Calendar.Month, y = input$Measure, type = "line", group = Calendar.Year, col = Calendar.Year)
不幸的是,该图表仅显示一个点.不需要输入$ Measure并在我的数据集中找到该字段.
Unfortunately, the chart renders with just one point. It's not taking input$Measure and finding that field in my data set.
我知道在使用ggplot时,我会将我的aes切换为aes_string.情节中有类似的解决方案吗?
I know when using ggplot, i'd switch my aes to aes_string. Is there a similar solution in 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")
)
)
)
)
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")
})
})
在上面的示例中,我可以使用下拉菜单在Var1和Var2之间切换.我的情节也随之改变.该代码使用ggplot及其aes_string函数进行输入.然后使用ggplotly函数将其转换为交互式绘图.
In the example above, I can use my drop down to switch between Var1 and Var2. My plot changes accordingly. The code uses ggplot and it's aes_string function to take an input. This is then converted into a plotly interactive plot using the ggplotly function.
有没有办法我可以使用plotly本地完成此操作?
Is there a way I can do this natively with plotly?
推荐答案
使用base :: get()函数:
Use base::get() function:
p <- plot_ly(data = data, x = ~Month, y = ~get(input$Measure), type = "line")
或使用ggplot相同:
or the same using ggplot:
p <- ggplot(data = data, aes(x = Month, y = get(input$Measure))) +
geom_line(size = 1.5) +
theme_minimal()
ggplotly(p)
这篇关于根据selectInput更改可绘制图表y变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!