I am trying to create an interactive scatter plot within Shiny using the plotly
library, where I can plot grouped data and move my cursor over each data point. I am new to plotly
but have used Shiny extensively.
Here is a mock example that I have came up with:-
library(shiny)
library(shinyWidgets)
library(plotly)
library(tidyverse)
ui<-fluidPage(
titlePanel("Iris"),
tabsetPanel(
tabPanel("Iris scatter",
sidebarPanel(width=5,
h5("Select the axis variables"),
selectInput("eda_scatter_x", "Select x-axis",
c("Sepal Length"="Sepal.Length",
"Sepal Width" ="Sepal.Width",
"Petal Length"= "Petal.Length",
"Petal Width"= "Petal.Width")),
selectInput("eda_scatter_y", "Select y-axis",
c("Sepal Length"="Sepal.Length",
"Sepal Width" ="Sepal.Width",
"Petal Length"= "Petal.Length",
"Petal Width"= "Petal.Width")),
actionButton(inputId = "eda_run", "Run analysis")),
mainPanel(
plotlyOutput("eda_scatter_graph")
)))
)
server <- function(input,output,session){
observeEvent(input$eda_run,{
output$eda_scatter_graph<- renderPlotly({
iris%>%
group_by(Species)%>%
summarise_at(vars(Sepal.Length:Petal.Width),mean)%>%
plot_ly(x=input$eda_scatter_x, y=input$eda_scatter_y, size=I(c(100,50)))%>%
add_markers()
})
})
}
shinyApp(ui,server)
Which gives this output:-
Desired output
What I want to be able to do is plot the grouped data points, so when my cursor moves over the data points, the markers are able to tell me the x-axis and y-axis coordinates plus the grouped variable name (in this case, the Species
). Lastly, I want to be able to update the x-axis and y-axis using the selectInput
boxes, but when you run the app, it does not update.
Can anyone show me what I am doing wrong and kindly suggest edits?
Thanks :)
CodePudding user response:
Dont use observe event but rather reactive values , and let plotly handle the rest internally
library(shiny)
library(plotly)
ui<-fluidPage(
titlePanel("Iris"),
tabsetPanel(
tabPanel("Iris scatter",
sidebarPanel(width=10,
h5("Select the axis variables"),
selectInput('xcol','X Variable', names(iris)),
selectInput('ycol','Y Variable', names(iris)),
selectInput('color','Group Color', names(iris)),
mainPanel(
plotlyOutput("eda_scatter_graph")
)
)
)
)
)
server <- function(input,output,session){
x <- reactive({
iris[,input$xcol]
})
y <- reactive({
iris[,input$ycol]
})
color <- reactive({
iris[,input$color]
})
output$eda_scatter_graph<- renderPlotly(
plot1<- plot_ly( x=x(), y=y(), type = 'scatter',
mode = 'markers', color = color())
)
}
shinyApp(ui,server)