logo
down
shadow

Create input$selection to subset data AND radiobuttons to choose plot type in Shiny


Create input$selection to subset data AND radiobuttons to choose plot type in Shiny

By : user2956140
Date : November 22 2020, 10:54 AM
this will help I've been trying to utilize shiny to create several visualizations for several different classes of data. Last night I was able to subset data but I do not know how to switch plot types with this data. I have the following data frame: , You need to use reactive functions.
ui.R:
code :
library(shiny)
ulist=levels(cd$Project)
names(ulist) = ulist
shinyUI(pageWithSidebar(
  headerPanel("Project Data"),
  sidebarPanel(
    radioButtons("pType", "Choose plot type:",
                 list("A", "B", "C")),
    selectInput("proj", "Project:",ulist)
  ),
  mainPanel(
    plotOutput("testPlot")
  )
)
)
library(shiny)
library(ggplot2)
library(lattice)

# Define shiny server
shinyServer(function(input, output) {
  pdata <- reactive({
    subset(cd, Project==input$proj)
  }
  )
  plotType <- reactive({
    switch(input$pType,
           A = hist,
           B = barplot,
           C = pie)
  })
  output$testPlot <- renderPlot({ 
    plotType()(pdata()[["Hours"]])
  })
})


Share : facebook icon twitter icon
Shiny input plot selection

Shiny input plot selection


By : Loredana Paganuzzi
Date : March 29 2020, 07:55 AM
help you fix your problem I have this code and I want to have a Select Input option to select from two different ways of plotting the graphic. , Like
code :
server <- function(input, output) {

    output$plot <- renderPlot({
        if(input$select=="Trend")
            plot(forecast(fit, #Confidence Interval %
                          level = c(input$range)),
                 sub= "Confidence Interval 70% ~ 90% or Determined by user", 
                 ylab= "Y Axis Variable",
                 main= "Forecast Linear Structural Model @ Trend-Wise",
                 ylim = c(0,400))
        else
            plot(forecast(fit2,
                          #Confidence Interval %
                          level = c(70,90)),
                 sub= "Confidence Interval 70% ~ 90% or Determined by user",
                 ylab= "Y Axis Variable",
                 main= "Forecast Linear Structural Model @ Level-Wise",
                 ylim = c(0,400))
    })

}
server <- function(input, output) {

    output$plot <- renderPlot({
        if(input$select=="Trend")
            method <- fit
        else 
            method <- fit2
        plot(forecast(method, #Confidence Interval %
                      level = c(input$range)),
             sub= "Confidence Interval 70% ~ 90% or Determined by user", 
             ylab= "Y Axis Variable",
             main= "Forecast Linear Structural Model @ Trend-Wise",
             ylim = c(0,400))

    })

}
Dynamically choose inputs based on reactive subset data in shiny

Dynamically choose inputs based on reactive subset data in shiny


By : Yves Germain
Date : March 29 2020, 07:55 AM
Does that help It took me a while to figure out your code. So:
1) Make use of renderUI which will allow you to dynamically create controls
code :
library(shiny)
library(plotly)

### 1. Create some sample data
myrows<-sample(letters,12)
exdata<- data.frame(mycat=rep(myrows,2),yr=rep(1:2,each=12),KPI_1=rnorm(24),
                    KPI_2=round(runif(24,1,20)),KPI_3=rbinom(24,6,0.5))


ui <- fluidPage(

  sidebarPanel(
    uiOutput("c1"),uiOutput("c2")),
  mainPanel(
    column(6,
    checkboxGroupInput("comp", "Categories",myrows,myrows,inline=TRUE),
    actionButton("go", "Update"),
    textOutput("txt"),
    tableOutput("head")),
    column(6,
    plotlyOutput("plot3", height = 300, width = 700)))
)

server <- function(input, output) {
  ### 3. Server part
  mydata <- eventReactive(input$go,{
    res<-subset(exdata,mycat%in%input$comp)
    return(res)
  })

  output$txt <- renderText({
    paste("You chose", paste(input$comp, collapse = ", "))
  })
  output$head <- renderTable({
    mydata()
  })

  conrolsdata <- reactive({
    unique(as.character(mydata()$mycat))
  })
  output$c1 <- renderUI({
    selectInput("cat_1", "Variable:",conrolsdata())
  })

  output$c2 <- renderUI({
    selectInput("cat_2", "Variable:",conrolsdata())
  })


  output$plot3 <- renderPlotly({

    if(is.null(input$cat_1)){
      return()
    }

    y1<- mydata()$KPI_1[as.character(mydata()$mycat) %in% input$cat_1]
    y2<- mydata()$KPI_2[as.character(mydata()$mycat) %in% input$cat_2]
    x0<-c(1,2)
     #use the key aesthetic/argument to help uniquely identify selected observations
     plot_ly(x = x0,y = y1, type="scatter",mode='lines+markers',name="Firm1") %>%
       add_trace(y = y2, name = "Firm2", mode = 'lines+markers') %>%
       layout(dragmode = "select")
  })

}

shinyApp(ui, server)
How to create a pop-up upon selection of points in a plot in a Shiny App

How to create a pop-up upon selection of points in a plot in a Shiny App


By : Imogene Abshear
Date : March 29 2020, 07:55 AM
it fixes the issue You can create a reactiveVal that contains the 'brushed points'. This requires an observer that updates this reactiveVal whenever the brushed points change. We can then create another observeEvent that listens to changes in our reactiveVal and make it trigger a modalDialog whenever new points are selected. Hope this helps!
By the way, you could also just let the observeEvent listen to input$plot1_brush, but then you would have to run brushedPoints(mtcars2, input$plot1_brush) twice, once for the renderText and once for the modalDialog, so I would suggest the approach with reactiveVal.
code :
library(ggplot2)
library(Cairo)   # For nicer ggplot2 output when deployed on Linux

mtcars2 <- mtcars[, c("mpg", "cyl", "disp", "hp", "wt", "am", "gear")]

ui <- fluidPage(
  fluidRow(
    column(width = 4,
           plotOutput("plot1", height = 300,
                      # Equivalent to: click = clickOpts(id = "plot_click")
                      click = "plot1_click",
                      brush = brushOpts(
                        id = "plot1_brush"
                      )
           )
    )
  ),
  fluidRow(
    column(width = 6
    ),
    column(width = 6,
           verbatimTextOutput("brush_info")
    )
  )
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    ggplot(mtcars2, aes(wt, mpg)) + geom_point()
  })

  selected_points <- reactiveVal()

  # update the reactiveVal whenever input$plot1_brush changes, i.e. new points are selected.
  observeEvent(input$plot1_brush,{
    selected_points( brushedPoints(mtcars2, input$plot1_brush))
  })

  # show a modal dialog
  observeEvent(selected_points(), ignoreInit=T,ignoreNULL = T, {
    if(nrow(selected_points())>0){
    showModal(modalDialog(
      title = "Important message",
      paste0("You have selected: ",paste0(rownames(selected_points()),collapse=', ')),
      easyClose = TRUE
    ))
    }
  })

  output$brush_info <- renderPrint({
    selected_points()
  })

  output$click_info <- renderPrint({
    nearPoints(mtcars2, input$plot1_click, addDist = TRUE)
  })
}

shinyApp(ui, server)
R Shiny - Using Selectinput as column selection to subset data frame

R Shiny - Using Selectinput as column selection to subset data frame


By : Ines
Date : March 29 2020, 07:55 AM
hop of those help? I think you can solve your issue by not using subset, since your column name is a variable. See the example below:
code :
A = 1
B ='am'

# This does not work
mtcars2 = subset(mtcars, B %in% A)

# This works
mtcars2 = mtcars[mtcars[,B] %in% A,]
data_vals = data_vals[data_vals[,input$filt1] %in% input$checkboxGroup1,]
Shiny/ggvis Reactivity to Subset Plot Data

Shiny/ggvis Reactivity to Subset Plot Data


By : user4827738
Date : March 29 2020, 07:55 AM
I hope this helps . Further search would indicate that this is a known bug for ggvis: https://github.com/rstudio/ggvis/issues/71
Related Posts Related Posts :
  • Selecting unique rows using sqldf package in R
  • why am i getting "month.observed" object not found even though it has been defined in R?
  • Using German characters (ü, ö, ä, etc.) in text analysis (R)
  • R JAGS: Dimension mismatch
  • R - How to create a function that accepts a code block as parameter?
  • How do I manually set geom_bar fill color in ggplot
  • How can I get my points to connect in a plot and show a trend with NA values in data?
  • Read SPecific lines of a CSV file in R-language
  • ggplot stacked bar plot from 2 separate data frames
  • auto.arima not parallelizing
  • Histogram of binned data frame in R
  • R rewriting stringmanipulations implemented in loop to the R-way
  • get first entries in rows of list?
  • Conditionally removing rows from a matrix in R
  • Using a loop to find P(-1.5<Y<1.5) for a range of sample sizes
  • R-Count and list the maximum count row by row
  • Include Iverson Bracket in R documentation
  • update a data frame and environment in R
  • How to write dynamic cumulative multiple in R
  • format time using as.POSIX in R
  • Change the class of multiple columns
  • Remove period and spaces within column headings nested in a list of data frames
  • R: error message --- package error: "functionName" not resolved from current namespace
  • labels with geom_text ggplot2
  • Passing mongodb ISODate in R
  • Importing "csv" file with multiple-character separator to R?
  • Change row names of a table obtained from a lm regression using xtable function
  • R language iterate over R object
  • How do you delete the header in a dataframe?
  • Re coding in R using complicated statement
  • accumulating functions and closures in R
  • How do you combine two columns into a new column in a dataframe made of two or more different csv files?
  • Twitter authentication fails
  • Summing Values of One Vector Conditional on Values of Another Vector
  • draw cube into 3D scatterplot in RGL
  • lme4 translate formula to code in 3-level model
  • How to draw single axis plot in R
  • Combine geom_tile() and facet_grid/facet_wrap and remove space between tiles (ggplot2)
  • Use snpStats with R version 3.0.1
  • Makefile gives strange error while compiling markdown file into .docx file
  • How to determine whether a points lies in an ellipse
  • Summarize data already grouped in r
  • Is the bigvis package for R not available for R version 3.0.1?
  • Operator overloading in R reference classes
  • How to enable user to switch between ggplot2 and gVis graphs in R Shiny?
  • Is there an easy way to separate categorical vs continuous variables into two dataset in R
  • Correct previous year by id within R
  • Installation of rdyncall package for R
  • ggplot2 plot that evaluates the percentage and mean of a third variable at intersecting points
  • Error Handling with Lapply
  • data.table - split multiple columns
  • How to compute the overall mean for several files in R?
  • R: Graph Plotting: Subscripts in the legend like LaTeX
  • Restructuring data in R
  • Distance of pointsfrom cluster centers after K means clustering
  • R incorrect value of date function
  • Package "Imports" not loading in R development package
  • r - run a user defined function several times by taking column elements as parameters
  • Generate crosstabulations from dataframe of categorical variables in survey
  • Restructure output of R summary function
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org