I am new to R Shiny. Actually i have drawn Stacked Barplot using ggplot in my
R code. I want to draw the same using shiny. Below is my R code:
ggplot(data = df, aes(x = OutPut, y = Group, fill = Group)) +
geom_bar(stat = "identity") +
facet_grid(~ Environment)
In my R code it is giving correct results.But i am trying to draw in shiny. Below is my shiny R code.
ui <- fluidPage(theme = shinytheme("lumen"),
titlePanel("Data Analysis"),
selectInput("variable", "Variable:", c("OutPut", "Member", "Levels")),
mainPanel(plotOutput("plot")))
# Define server function
server <- function(input, output){
x = ggplot(data = df, aes(x = variable.names(), y = Group, fill = Group)) +
geom_bar(stat = "identity") +
facet_grid(~ Environment)
plot(x)
}
# Create Shiny object
shinyApp(ui = ui, server = server)
It is throwing an error,here i have created a dropdown box where all the variables have been stored. So when i select one variable, it should plot the Stacked barplot. Could anyone please help me.
Like it was mentioned in the comments, you need to use the rendering functions and actually assign them to the output to get the outputs you need.
I believe an example of using plots in rshiny would help, since it wouldn't make sense to have it in the comments, here it is:
library(shiny)
library(ggplot2)
ui <- fluidPage(titlePanel("Fast Example with mtcars"),
# inputs
selectInput("x", "Choose x:", choices = names(mtcars), selected = 'mpg'),
selectInput("y", "Choose y:", choices = names(mtcars), selected = 'hp'),
selectInput("fill", "Choose fill:", choices = names(mtcars), selected = 'carb'),
mainPanel(
#outputs
h2("Chosen variables are:"),
h4(textOutput("vars")),
plotOutput("plot")))
server <- function(input, output) {
df <- mtcars
# here's how you would use the rendering functions
# notice that I used aes_string
output$plot <- renderPlot({
ggplot(data=df,
aes_string(x= input$x, y= input$y, fill=input$fill)) +
geom_point()
})
output$vars <- renderText(paste0('x: ', input$x, " , ",
'y: ', input$y, " , ",
'fill: ', input$fill))
}
shinyApp(ui = ui, server = server)
The Rshiny tutorial is pretty helpful, you can take a look at it here https://shiny.rstudio.com/tutorial/
Related
So, I need to make a shiny app that takes a dynamic number of inputs to eventually do dimension reduction, but I'm stuck trying to figure out how to refer to what's in my inputs when I have a dynamic number of them. I'm using the iris dataset and the inputs are the variables. Part of what I need to do is plot 2 of them with a k means, but I'm just trying to 1st make a basic plot. What I have so far is
library(shiny)
library(ggplot2)
ui <- shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
fluidRow(
column(2,
textInput(inputId = "number", label = "number of selectInput",value = 2)
),
column(8,
plotOutput("distPlot")),
column(2,
uiOutput(outputId = "putselect"))
)
))
server <- shinyServer(function(input, output) {
output$putselect = renderUI(
if(input$number != 0 ){
lapply(1:(input$number), function(i){
selectInput(inputId = paste0("var",i), label = paste0("input ",i), choices = names(iris))
})
}
)
output$distPlot <- renderPlot({
ggplot(iris, aes(x = input$var1, y = input$var2, color = Species)) +
geom_point()
})
})
shinyApp(ui = ui, server = server)
In my output$distplot what goes in the ggplot x and y? The way I have it now it shows up and the labels on the graph change, but there are no points on the graph. I'm new to using Shiny so any help would be appreciated.
instead of aes use aes_string like:
ggplot(iris, aes_string(x = input$var1,
y = input$var2,
color = "Species"
)
)
note to quote the variables supplied as a string (Species in this case)
see: Shiny: passing input$var to aes() in ggplot2
I wasted hours to find out why my plot is automatically updating itself when I change inputs while it was supposed to wait for the Run button but it simply ignored that step and I ended up finally finding ggplot as the trouble maker!!! This is my minimal code:
library(ggplot2)
library(tidyverse)
varnames <- names(cars)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fluidRow(
column(
width = 12,
# Variables Inputs:
varSelectInput("variables", "Select Input Variables", cars, multiple = TRUE),
selectizeInput("outvar", "Select Output Variable", choices = varnames, "speed", multiple = F),
# Run Button
actionButton(inputId = "run", label = "Run")
)
)
),
# Main panel for displaying outputs ----
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
df <- reactive({
cars %>% dplyr::select(!!!input$variables, input$outvar)
})
plt <- eventReactive(input$run, {
#Just creating lm formula
current_formula <- paste0(input$outvar, " ~ ", paste0(input$variables, collapse = " + "))
current_formula <- as.formula(current_formula)
#Fitting lm
fit <- lm(current_formula, data = df())
pred <- predict(fit, newdata = df())
#Plotting
ggplot(df(), aes(df()[, input$outvar], pred)) +
labs(x = "Observed", y = "Predicted") +
geom_point() +
theme_bw()
#plot(df()[, input$outvar], pred) #This one works fine!!!!
})
output$plot <- renderPlot({
plt()
})
}
# Run the application
shinyApp(ui = ui, server = server)
If you run this, you'll notice that ggplot doesn't care anymore about the Run button after the 1st run and it keeps updating as you change the inputs!! However, if you use the simple base plot function (which I put in a comment in the code) there wouldn't be any problems and that works just fine! Sadly I need ggplot in my app because base plot is ugly. I am seeing suggestion for using isolate() to solve this issue but I have no clue where isolate() should be put to fix my problem also it doesn't make sense to use isolate() when base plot function works fine without it and it's the ggplot that makes the problem. Any explanation would be appreciated.
The issue is that ggplot aesthetics are lazy evaluated. You really want to put symbols into the aes() rather that reactive data values. Change your plotting code to
ggplot(df(), aes(.data[[input$outvar]], pred)) +
labs(x = "Observed", y = "Predicted") +
geom_point() +
theme_bw()
With ggplot you use the .data pronoun to access the current data source rather than trigger the reactive df() object again.
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)))
)
The ggplot2 object doesnt display properly in RShiny mainpanel. For recreation, the below code uses iris dataset. Need help
I checked the link - RShiny ggplot2 not showing , but this didnt help. I also ran through https://shiny.rstudio.com/ website, but nothing had explanation with example on how to display the ggplot2 object. I used renderPlot and renderImage functions, but none gave required results.
'''
library(shiny)
library(shinydashboard)
ui <- fluidPage(titlePanel("Sample Shiny"),
navbarPage(
br(),
tabPanel(h4("Iris Data"),
sidebarPanel(
radioButtons("var1",
label = "Choose a FILL field",
choices = c("Species"),
selected = "Species"),
mainPanel(plotOutput("plot",click = "plot_click")))
)
))
server <- function(input, output) {
output$plot <- renderPlot(
{
#browser()
sw <- input$var1
### "a" below is iris dataset which I pass on as input**
ggplot(data = a) +
aes(x = Sepal.Length, fill = sw) +
geom_bar() +
theme_minimal() +
coord_flip()
},width = "auto",height = "auto",res = 72)
}
# Run app ----
shinyApp(ui, server)
'''
I was hoping to see the graph in the middle of mainpanel, but all I see is a small graph with no proper margins.
Expected: (Something like this on RShiny)
Here is what I see now:
input$var1 is a string => use aes_string:
ggplot(data = a) +
aes_string(x = "Sepal.Length", fill = sw) + ......
I have tried to plot the graph separately using ggplot (outside the shiny app) and it plots well so I know the problem is not with my ggplot code but with how the inputs in the shiny app are entered into the renderplot({}) section. The inputs are the axes.
Code:
library(ggplot2)
library(shiny)
data1 <- mtcars
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "xaxis",
label = "Choose a Variable for the X-axis of the First Graph",
choices = colnames(data1)
),
selectInput(
inputId = "yaxis",
label = "Choose a Variable for the Y-axis of the First Graph",
choices = colnames(data1)
)
),
mainPanel(
plotOutput(outputId = "scatterplot"))
)
)
server <- function(input, output) {
output$scatterplot <- renderPlot({
req(input$xaxis)
req(input$yaxis)
ggplot(data1, aes(x = input$xaxis, y = input$yaxis))+geom_point()
})}
shinyApp(ui = ui, server = server)
Solution
You are passing a string to your aes, which does not work. You should try
server <- function(input, output) {
output$scatterplot <- renderPlot({
req(input$xaxis)
req(input$yaxis)
gggplot(data1, aes_string(x = paste0("`", input$xaxis, "`"),
y = paste0("`", input$yaxis, "`"))) + geom_point()
})
}
Explanation
aes expects the bare column name like in ggplot(mtcars, aes(am, vs)) + geom_point(). Note that we do not use quotatation marks " for am or vs (i.e. we are passing variable names and not strings). On the other hand input$xaxis returns a string. Thus, you have to use aes_string which is meant for working with strings rather than column names.
Update
Added backtricks to deal with non standard names.