Adding a moving vline in a Shiny Application (based on user input) - r

I have the following shiny application:
library(shinydashboard)
library(ggplot2)
library(dplyr)
UI <- dashboardPage(
dashboardHeader(title = ""),
dashboardSidebar(
),
dashboardBody(
mainPanel(
actionButton("goButton", "Go!"),
plotOutput("plot_timeseries")
)
)
)
Server <- function(input, output) {
output$plot_timeseries <- renderPlot({
ggplot(mtcars, aes(mpg, disp)) + geom_point()+
scale_x_continuous(limits = c(0,35)) +
geom_vline(xintercept = 1)
})
}
shinyApp(ui = UI, server = Server)
As you'll see I have a vline now at x = 1. However what I would like to achieve it that when I press the "go" button a counter should be initiated (adding 1 with every second). So 5 seconds after pressing the go button the variable should 6 and the vline value should be 6.
Any thoughts on how I can get this working in the example above?

Here is a possible solution, which uses two reactiveVal's; one to keep track of whether the counter should increment, and one with the current value of the counter.
Hope this helps!
library(shiny)
library(shinydashboard)
library(ggplot2)
library(dplyr)
UI <- dashboardPage(
dashboardHeader(title = ""),
dashboardSidebar(
),
dashboardBody(
mainPanel(
actionButton("goButton", "Go!"),
plotOutput("plot_timeseries")
)
)
)
Server <- function(input, output, session) {
counter <- reactiveVal(1)
action <- reactiveVal(FALSE)
# When goButton is clicked, set action() from FALSE to TRUE or the other way around.
observeEvent(input$goButton,
{
action(!action())
})
# Add an oberserver that invalidates every second, and increments the counter if action()==TRUE
observe({ invalidateLater(1000, session)
isolate({
if(action())
{
# Add 1 to our counter
counter(counter() + 1)
}
})
})
output$plot_timeseries <- renderPlot({
ggplot(mtcars, aes(mpg, disp)) + geom_point()+
scale_x_continuous(limits = c(0,35)) +
geom_vline(xintercept = counter())
})
}
shinyApp(ui = UI, server = Server)

Related

Display text in shiny app using ggplotly()

Is there a way to display text in shiny app through ggplotly()?I want to pass some features that require ggplotly() later and I would like to know if this is possible.
library(plotly)
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("HTML"),
sidebarLayout(
sidebarPanel(
),
mainPanel(
textOutput("testHTML"),
plotlyOutput("PLOTLYTEXT")
)
)
))
server <- shinyServer(function(input, output) {
output$testHTML <- renderText({
"text"
})
output$PLOTLYTEXT<-renderPlotly({
p<-renderText({
"text"
})
ggplotly(p)
})
})
shinyApp(ui = ui, server = server)
As I mentioned in my comment one option to display text via ggplotly would be to create a ggplot using e.g. a geom_text to display your text which could then be converted to a plotly object:
library(plotly)
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("HTML"),
sidebarLayout(
sidebarPanel(
),
mainPanel(
textOutput("testHTML"),
plotlyOutput("PLOTLYTEXT")
)
)
))
server <- shinyServer(function(input, output) {
output$testHTML <- renderText({
"text"
})
output$PLOTLYTEXT<-renderPlotly({
p <- ggplot(data.frame(x = 1, y = 1, label = "text")) +
geom_text(aes(x = x, y = y, label = label)) +
theme_void()
ggplotly(p)
})
})
shinyApp(ui = ui, server = server)
#>
#> Listening on http://127.0.0.1:8289

Plotly output in Shiny "Error: argument 1 is not a vector"

I'm trying to make an interactive plot in my Shiny app. I thought it would be simple enough to use plotly::plotlyOutput and plotly::renderPlotly, but I keep getting Error: argument 1 is not a vector. I wonder if you can help?
library(shiny)
library(tidyverse)
library(plotly)
daysSince10 <- read_csv("https://raw.githubusercontent.com/joegoodman94/CoronavirusTracker/master/days.csv")
ui <- fluidPage(
titlePanel("Coronavirus Tracker"),
sidebarLayout(
sidebarPanel(selectInput('Country', 'Select Countries', multiple = T, unique(daysSince10$`Countries and territories`))),
mainPanel(
tabsetPanel(
tabPanel("Plot", plotly::plotlyOutput('trend')),
tabPanel("Table", tableOutput('table'))
)
)
)
)
server <- function(input, output, session) {
observe({
moddays <- daysSince10[daysSince10$`Countries and territories` %in% input$Country,]
output$trend <- plotly::renderPlotly({
ggplot(moddays) +
geom_line(aes(x = `Number of days since 10th death`, y = `Total Deaths`, color = `Countries and territories`)) +
scale_y_log10()
})
})
}
shinyApp(ui = ui, server = server)
The plot is working fine, the problem is when you lack any country to graph on it, here is a really cool solution using the validate function
library(shiny)
library(tidyverse)
library(plotly)
daysSince10 <- read_csv("https://raw.githubusercontent.com/joegoodman94/CoronavirusTracker/master/days.csv")
ui <- fluidPage(
titlePanel("Coronavirus Tracker"),
sidebarLayout(
sidebarPanel(selectInput('Country', 'Select Countries', multiple = T, unique(daysSince10$`Countries and territories`))),
mainPanel(
tabsetPanel(
tabPanel("Plot", plotly::plotlyOutput('trend')),
tabPanel("Table", tableOutput('table'))
)
)
)
)
server <- function(input, output, session) {
observe({
moddays <- daysSince10[daysSince10$`Countries and territories` %in% input$Country,]
output$trend <- plotly::renderPlotly({
validate(
need(input$Country, "please select a country")
)
ggplot(moddays) +
geom_line(aes(x = `Number of days since 10th death`, y = `Total Deaths`, color = `Countries and territories`)) +
scale_y_log10()
})
})
}
shinyApp(ui = ui, server = server)

ggplot not showing - area is blank

I am relatively new to ggplot2 and I have created a plot based on a csv file.
The problem I am having is that the plot is blank:
Nothing shows expect the title and I am not sure why!
As you can see the data is fine within RStudio:
My csv file is in the same directory as my app.R file:
My working directory is the same folder:
So why is ggplot2 failing to pick up the data held within the csv file?
Here is my code:
library(shiny)
library(ggplot2)
ui <- (fluidPage(
titlePanel("Pig Breeding")
)
)
mainPanel(
plotOutput(outputId = "scatterplot")
)
server <- (function(input, output){
output$scatterplot <- renderPlot({
pig_plot <- ggplot(read.csv("pigs_data.csv"),
aes_string(x = "species", y = "sow_count") +
geom_point())
})
})
shinyApp(ui, server)
the below code works with a test data called iris. Your mistake lies in your
ui <- (fluidPage(
titlePanel("Pig Breeding")
)
)
mainPanel(
plotOutput(outputId = "scatterplot")
)
ui code. You have left your mainPanel out of the fluidpage parenthesis. Thus, it does not read the plotOutput.
Example
library(shiny)
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Iris data"),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
# Define server logic
server <- function(input, output) {
output$distPlot <- renderPlot({
ggplot(iris, aes(x=Sepal.Width, y=Petal.Width)) + geom_point()
})
}
# Run the application
shinyApp(ui = ui, server = server)
The code below should work for your question.
library(shiny)
# Define UI for application
ui <- fluidPage(
# Application title
titlePanel("Pig Breeding"),
# Show a plot of the generated distribution
mainPanel(
plotOutput("scatterplot")
)
)
# Define server logic
server <- function(input, output) {
output$scatterplot <- renderPlot({
ggplot(read.csv("pigs_data.csv"),
aes(x = "species", y = "sow_count")) + geom_point()
})
}
# Run the application
shinyApp(ui = ui, server = server)

How to create a graph up in Shiny Application

I have the following Shiny Application:
library(shiny)
library(shinyjs)
library(shinydashboard)
UI <- fluidPage(
actionButton("create_popup1", "Create a text popup"),
actionButton("create_popup2", "Create a graph popup")
)
Server <- function(input, output){
observeEvent(input$create_popup1, {
showModal(modalDialog(
title = "test", "this is a test"
))
})
observeEvent(input$create_popup2, {
showModal(modalDialog(
p <- ggplot(mtcars, aes(x = mpg, x= disp)) + geom_point()
))
})
}
shinyApp(ui = UI, server = Server)
As you'll the first button works (and gives a pop up with text). However the second gives an erorr. Any thoughts on what I should change to get a graph as a pop up?
Something like this should work:
library(shiny)
library(ggplot2)
library(shinyjs)
library(shinydashboard)
UI <- fluidPage(
actionButton("create_popup1", "Create a text popup"),
actionButton("create_popup2", "Create a graph popup")
)
Server <- function(input, output){
observeEvent(input$create_popup1, {
showModal(modalDialog(
title = "test", "this is a test"
))
})
observeEvent(input$create_popup2, {
showModal(modalDialog(
plotOutput("plot")
))
})
output$plot <- renderPlot({
p <- ggplot(mtcars, aes(x = mpg, y= disp)) + geom_point()
p
})
}
shinyApp(ui = UI, server = Server)

Using shiny to highlight specific bar in a bar chart

I am not sure if Im doing this the right way (I am open for suggestions!). However what I try to do if to create a Shiny app where i can pick a bar and then the bar should be highlighted in the graph.
For this example I use the titanic_train dataset.
I do:
library(shiny)
library(ggplot2)
library(titanic)
library(dplyr)
UI <- fluidPage(
# Application title
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
selectInput("specific_bar", "Pick bar to highlight:",
choices = unique(titanic_train$Embarked))
),
mainPanel(
plotOutput("plot_nice")
)
)
)
Server <- function(input, output) {
filtered <- reactive({
titanic_train$Specific <- ifelse((titanic_train$Embarked == input$specific_bar), 1,0)
})
output$plot_nice <- renderPlot({
ggplot(filtered(), aes_string(x="Embarked", y="Survived", fill = "Specific")) +
geom_bar(stat = "identity")
})
}
shinyApp(ui = UI, server = Server)
Running this however gives me the following error:
ggplot2 doesn't know how to deal with data of class numeric
And the problem really seems to have to do with the filtered() reactive function. Any thoughts on what is going wrong here?
you have to ask for the data.frame object back in the reactive part,
what you were doing is getting a vector back instead of getting another column added to titanic_train.
this should fix it:
library(shiny)
library(ggplot2)
library(titanic)
library(dplyr)
UI <- fluidPage(
# Application title
titlePanel("Hello Shiny!"),
sidebarLayout(
sidebarPanel(
selectInput("specific_bar", "Pick bar to highlight:",
choices = unique(titanic_train$Embarked))
),
mainPanel(
plotOutput("plot_nice")
)
)
)
Server <- function(input, output) {
filtered <- reactive({
titanic_train$Specific <- ifelse((titanic_train$Embarked == input$specific_bar), 1,0)
return(titanic_train)
})
output$plot_nice <- renderPlot({
ggplot(filtered(), aes_string(x="Embarked", y="Survived", fill = "Specific")) +
geom_bar(stat = "identity")
})
}
shinyApp(ui = UI, server = Server)

Resources