shiny dashboard selectizeInput and plots - r

I'am trying to create a shiny application about the Tunisian elections,
i put the political party as a widgets, so the user can choose one or multiple politicals parties and the application will show a plot of the number of votes of each political party, I have succeeded in the case of choosing one political party but when the user choose more than one, it failed :(
undermentioned the code R concerning the plot :
selectizeInput("parti", label = "Parti politique", choices= levels(data$Q99), selected = "Nidaa Tounes",multiple=TRUE)
#server.R
library(shiny)
library(Rcmdr)
library(ggplot2)
library(ggalt)
data <- readXL("C:/Users/boti/Desktop/regression/bfinal.xlsx",rownames=FALSE, header=TRUE, na="NA", sheet="imp", stringsAsFactors=TRUE)
shinyServer(function(input, output) {
dataa<-reactive({as.data.frame(data)})
#Parti politique
partii=reactive({
as.character(input$parti)
})
output$plot1=renderPlot({
n=as.data.frame(table(dataa()[,95]))
n$Var1[n$Var1==partii()]
ggplot(n, aes(x =n$Var1[n$Var1==as.list(partii())] , y = n$Freq[n$Var1==as.list(partii())])) + geom_bar(stat = "identity", fill="Orange") + labs(title="Vote") +labs(x="Partis Politiques", y="Nombre de votes")
})
})

This example uses the mpg dataset to do what I guess you are trying to do. With the selectize input a user selects one or more manufacturers and the barplot displays the number of cars for the selected manufacturers:
ui.R
library(shiny)
library(ggplot2)
shinyUI(fluidPage(
titlePanel("Example"),
fluidRow(
column(3,
selectizeInput("mpgSelect",
label = "Select manufacturer",
choices = levels(as.factor(mpg$manufacturer)),
selected = "audi",
multiple=TRUE))),
fluidRow(
mainPanel(plotOutput('coolplot'),width = '40%'))
))
server.R
library(shiny)
library(ggplot2)
library(dplyr)
shinyServer(function(input, output) {
mpgSubset <- reactive({
validate(
need(input$mpgSelect != "", 'Please choose at least one feature.')
)
filter(mpg, manufacturer %in% input$mpgSelect)
})
output$coolplot<-renderPlot({
gg <- ggplot(mpgSubset(), aes(x = manufacturer, y = ..count..))
gg <- gg + geom_bar()
print(gg)
})
})

Related

creating a barplot with shiny that shows a new plot each time a region is selected

I am trying to create an interactive bar plot , however my skills on shiny are not the best. I have attempted to get something working but I am struggling - the server section starts to confuse me a bit.
Below are the sets of user inputs I am trying to include in the interactive plot:
A select input that allows you to select a region, and when this selection is made an entirely new plot appears (showing the demographics for that particular region only).
A slider input that allows you to slide across a range of age groups. For example - you may only want to select a range of the ages from '0 to 10' and '40 to 44'.
Below I have created a reproducible example that you can copy and paste. Please note the age ranges in my main dataset are not at equal intervals, nor is there enough data so that every location has a full set of age ranges. All i have done is try create a small version of a larger dataset I have.
library(dplyr)
library(ggplot2)
library(shiny)
library(shinyWidgets)
# creating example data
exampledata <- data.frame(City=c("London","Liverpool","Manchester",
"Porstmouth","Liverpool","Leeds",
"London","Manchester","Nottingham"),
Ageband = c("35 to 39","80+","40 to 44",
"0 to 10","80+","35 to 39",
"40 to 44","0 to 10", "80+"),
count = c(1200,800,520,
300,105,630,
410,150,700))
# Static Plot to show what I intend to make interactive
ggplot(exampledata, aes(fill=Ageband, y=count, x=Ageband)) +
geom_bar(position="dodge", stat="identity", show.legend = FALSE) +
facet_wrap(~City)+
labs(y="Participant count", x=" ",caption=(paste0("Participants sampled = ", sum(exampledata$count))))+
scale_fill_manual(name="Age",values=c("#CEE0F1", "#C3DAEE" ,"#B3D3E8" ,"#A2CBE2", "#8FC1DD" ,"#79B6D9" ,"#66AAD4" ,"#559FCD" ,"#4493C6", "#3686C0", "#2878B9","#1C69AF" ,"#1257A1" ,"#084594", "#05337d"))+
theme(plot.title = element_text(hjust = 0.5))+
theme(axis.text.x = element_text(angle = 90))
# shiny attempt
ui <- fluidPage(
titlePanel("Age Distribution of Research"),
selectInput("location", "Select Location", choices = exampledata$City),
sliderTextInput("age", "Select Age", choices = exampledata$Ageband)
plotOutput("bar")
)
server <- function(input, output, session) {
# At this point would you need to create a reactive expression or not?
data <- reactive({
exampledata %>%
filter(City == input$City)
})
# At which point of the plots do the inputs need specifying?
output$plot <- renderPlot({
ggplot(data, aes(aes(fill=Ageband, y=count, x=input$age)) +
geom_bar(position="dodge", stat="identity", show.legend = FALSE)
})
}
}
shinyApp(ui = ui, server = server)
Does this come close to what you want?
library(dplyr)
library(ggplot2)
library(shiny)
library(shinyWidgets)
exampledata <- data.frame(City=c("London","Liverpool","Manchester",
"Porstmouth","Liverpool","Leeds",
"London","Manchester","Nottingham"),
Ageband = c("35 to 39","80+","40 to 44",
"0 to 10","80+","35 to 39",
"40 to 44","0 to 10", "80+"),
count = c(1200,800,520,
300,105,630,
410,150,700))
ui <- fluidPage(
titlePanel("Age Distribution of Research"),
selectInput("location", "Select Location", choices = exampledata$City, selected="London", multiple=TRUE),
# Slider inputs work with numeric data, not categorical data
selectInput("age", "Select Age", choices = exampledata$Ageband, selected="35 to 39", multiple=TRUE),
plotOutput("plot")
)
server <- function(input, output, session) {
data <- reactive({
exampledata %>%
filter(
City %in% input$location,
Ageband %in% input$age
)
})
output$plot <- renderPlot({
req(input$age, input$location)
data() %>%
ggplot(aes(fill=City, y=count, x=Ageband)) +
geom_bar(position="dodge", stat="identity")
})
}
shinyApp(ui = ui, server = server)

Shiny: Create multiple tabs with separate inputs on each

I am building a shiny application with several tabs, each tab takes a user input (unique(data_in$cat), and generates some type of graph. The problem occurs in the second tab--for some reason, it does not generate the graph that is specified by data2. The first graph on the first tab is being displayed correctly.I see no error when I run this code, so I don't know where to start debugging!
library(shiny)
library(openxlsx)
library(ggplot2)
data_in <- read.xlsx("www/dem_data_clean.xlsx")
ui <- navbarPage(title = "Data",
tabPanel(title = "Over-all trends",
plotOutput("Histall"),
selectInput("Indall","Demographic Variable of Interest",choices = unique(data_in$cat))
),
tabPanel(title = "2017-2018"),
plotOutput("Hist17"),
selectInput("Ind17","Demographic Variable of Interest",choices = unique(data_in$cat))
)
server <- function(input, output, session) {
data1 <- reactive({
a <- subset(data_in,cat==input$Indall)
return(a)
})
data2 <- reactive({
a <- subset(data_in,cat==input$Ind17)
return(a)
})
output$Histall <- renderPlot({
ggplot(data1(), aes(x=Year,y=value, group =name, color=name)) + geom_line(stat = "identity") +
ylab("Percent of Population")
})
output$Hist17 <- renderPlot({
data2() %>%
filter(Year=="2017-18") %>%
ggplot(aes(name, value)) + geom_bar(stat = "identity")
})
}
shinyApp(ui, server)
Any suggestions to what I am doing wrong? I've tried playing around with different things for a few hours now to no avail!
The UI code is not correct, second plotOutput and selectInput are not within second tabPanel. It works if you fix it :
ui <- navbarPage(title = "Data",
tabPanel(title = "Over-all trends",
plotOutput("Histall"),
selectInput("Indall",
"Demographic Variable of Interest",
choices = unique(data_in$cat))
),
tabPanel(title = "2017-2018",
plotOutput("Hist17"),
selectInput("Ind17",
"Demographic Variable of Interest",
choices = unique(data_in$cat)))
)

Define column values as input for reactive shiny plot

I want to start a shiny app for practice where a use can choose from a dropdown the values in the "cut" column from the diamonds dataset (from ggplot2).
My ui looks as following:
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Reactive Boxplot"),
# Show a boxplot of the selected cut
mainPanel(
selectInput("column", label = h3("Column to plot"),
choices = c("", diamonds$cut),
selected = 1,
width='55%',
multiple = FALSE),
plotOutput("diamondshist")
)
)
)
I don't know how to define the input variables as the five distinct values in the "cut" column of diamonds dataset. Any input on this?
My server file looks like shared below. I assume I would also need to adapt the input data for the plot.
library(shiny)
library(ggplot2)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
compute_plot <- reactive({
if (input$column != ""){
ggplot(diamonds[, input$column])+
labs(title = "From diamonds dataset")+
geom_boxplot(aes(x = cut, y = price))+
scale_y_reverse()
}
})
output$diamondshist <- renderPlot({
compute_plot();
})
})
I assume this is what you are after:
pass the levels of diamonds$cut as input selection
subset the diamonds dataset to the selected cut
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
ui=shinyUI(fluidPage(
# Application title
titlePanel("Reactive Boxplot"),
# Show a boxplot of the selected cut
mainPanel(
selectInput("column", label = h3("Column to plot"),
choices = c("", levels(diamonds$cut)),
selected = NULL,
width='55%',
multiple = FALSE),
plotOutput("diamondshist")
)
)
)
# Define server logic required to draw a histogram
server=shinyServer(function(input, output) {
compute_plot <- reactive({
if (input$column != ""){
ggplot(subset(diamonds, cut==input$column))+
labs(title = "From diamonds dataset")+
geom_boxplot(aes(x = cut, y = price))+
scale_y_reverse()
}
})
output$diamondshist <- renderPlot({
compute_plot();
})
})
shinyApp(ui = ui, server = server)

checkbox not selected in a shiny app

I need to prepare a shiny app for a school project.
This is a link of what it is supposed to look like
https://yuvaln.shinyapps.io/olympics/
If you look at the app you see there is a checkbox named medals.When you
open the app they are all selected but in the event the user decides to uncheck them all there should be a small error and no graph should be drawn.
I am having trouble getting to this, when I uncheck all the boxes in my app
it draws an empty drawing
This is the important part of the code:
fluidRow(
column(3,checkboxGroupInput("Medals", label = strong("Medals"),
choices = list("Total" = "TOTAL", "Gold" = 'GOLD',
"Silver" = 'SILVER','Bronze'='BRONZE'),
selected = c('TOTAL','GOLD','SILVER','BRONZE')))),
fluidRow(
mainPanel(plotOutput('coolplot'),width = '40%'))
)
)
server <- function(input, output){output$coolplot<-renderPlot(plot.medals2(input$country,
input$Startingyear,input$Endingyear,input$Medals))}
shinyApp(ui = ui, server = server)
I am using a function plot.medals2 that gets a vector of medals ,start year, ending year, country and returns a drawing of the graph.
Since you didn't post the complete code, I have recreated an example using the Iris data set. I guess the code below answers your question...
library(shiny)
library(ggplot2)
library(dplyr)
ui <- shinyUI(fluidPage(
# Application title
titlePanel("Checkbox example"),
fluidRow(
column(3,checkboxGroupInput("example", label = strong("Species"),
choices = levels(iris$Species),
selected = levels(iris$Species)))),
fluidRow(
mainPanel(plotOutput('coolplot'),width = '40%'))
))
server <- shinyServer(function(input, output) {
irisSubset <- reactive({
validate(
need(input$example != "", 'Please choose at least one feature.')
)
filter(iris, Species %in% input$example)
})
output$coolplot<-renderPlot({
gg <- ggplot(irisSubset(), aes(x = Species, y = Sepal.Length))
gg <- gg + geom_boxplot()
print(gg)
})
})
# Run the application
shinyApp(ui = ui, server = server)

Select a point on ggplot

I'm trying to add a feature where the user can look at a plot of all time stamps from several patients of a certain variable, select a point and see which patient that point belongs to, as well as all other information about the patient at that time stamp. My data is reactive because the SQL Query that fetches it requires user input. I'm trying to use click in plotOutput and nearPoints in the server, and the clicker will show up when hovered over the plot, although if I try to click on a point, nothing will happen (the data display will remain null). Here is what I have:
#ui.R
library(shiny)
library(ggplot2)
shinyUI(navbarPage("Choose Page",
tabPanel("Page 1",
#sidebar
sidebarLayout(
sidebarPanel(
*unrelated tab*
)
)
),
tabPanel("Overall Metrics",
sidebarLayout(
sidebarPanel(
h3("Metrics Across All Patients"),
selectInput("selecty1",
label = "Choose a variable to display on the y-axis:",
choices = list('Var1', 'Var2', 'Var3', 'Var4')),
dateRangeInput("dates1", label= "Date Range:"),
submitButton("Create Graph"),
),
mainPanel(
plotOutput('plot1', click = "plotClick"),
verbatimTextOutput("click_info")
)
)
)
)
)
#server.R
library(shiny)
require(RODBC)
library(ggplot2)
library(quantmod)
library(reshape)
shinyServer(function(input, output) {
chan2 <- odbcConnect('date_base', uid='username')
queryString2 <- reactive({sprintf("**SQL Query**",input$dates1[1],input$dates1[2])})
overallData <- reactive({sqlQuery(chan2, queryString2())})
output$heartplot1 <- renderPlot({
ggplot(overallData(), aes_string(x = "Time_Stamp", y = input$selecty1)) + geom_point(size=2) + geom_line(aes(colour = factor(PatientNum))) + theme_bw() + stat_smooth(method="lm",se=FALSE,size=1)
})
output$click_info <- renderPrint({
nearPoints(overallData(), input$plotClick, addDist = FALSE)
})
})
All demos I find of nearPoints use typical data tables, how can I make this work with reactive data, or is that not the problem here?

Resources