I am trying to show the top ten highest temps from each year but the way I coded it, it will not change and just stays the same.
server.R
library(shiny)
library(dplyr)
library(ggplot2)
library(plotly)
library(readr)
library(tidyverse)
temp_df <-read_csv("~/Environment_Temperature_change_E_All_Data_NOFLAG.csv")
year_df <- temp_df[,8:66] #for the widget
info_df <- temp_df %>%
select(Area, Months, Element)
combine_df <- mutate(info_df, year_df)
combine_df <- na.omit(temp_df) # Get rid of NA rows
combine_df <- temp_df[!grepl("Standard Deviation",temp_df$Element), ] # Get rid of SD rows
top_ten_df <-top_n(combine_df, 10)
# Define server
server <-shinyServer(function(input, output) {
observe({
output$selected_var <- renderText({
paste("You have selected", input$year)
})
output$scatter <- renderPlot({
ggplot(data = top_ten_df, aes(x= Months, y = `Area`)) +
geom_point(aes(col=`Area`))
})
output$data <- renderTable({
final_df <-top_ten_df%>%
select(Area, Months, Element, input$year)
brushedPoints(final_df, input$plot_brush)
})
output$plotlyscatter <- renderPlotly({
plot_ly(data = top_ten_df, x = ~Area, y = ~Months, color=~Area, type = "scatter")
})
})
})
ui.R
library(shiny)
library(dplyr)
library(ggplot2)
library(plotly)
library(readr)
library(tidyverse)
temp_df <-read_csv("~/Environment_Temperature_change_E_All_Data_NOFLAG.csv")
year_df <- temp_df[,8:66] #for the widget
info_df <- temp_df %>%
select(Area, Months, Element)
combine_df <- mutate(info_df, year_df)
# Define UI
ui <- shinyUI(navbarPage(inverse = T, "Rising Temperatures",
tabPanel( "Top Ten Highest Tempratures",
sidebarLayout(
sidebarPanel(
h5("Selection"),
selectInput(inputId = "year",
label = "Select the year:",
choices = names(year_df),
),
textOutput("selected_var"),
),
mainPanel(
plotOutput(outputId = "scatter", brush = "plot_brush"),
tableOutput(outputId = "data"),
plotlyOutput(outputId = "plotlyscatter")
)
)
)
)
)
Also, I do not know where to use the app.R in this situation, sorry I am a bit new to all of this. I would like this to be an interactive scatter plot that when you pick an input from the widget.
Related
I need to control the number of chart using a slideInput.
I have a list with ggplot charts. Once my slider came from 1 to 2 it will display the first 2 charts of this list. If the slider range is from 1:3 it will display the first 3 charts from this list chart.
This is what Ive done so far:
library(shiny)
library(gapminder)
library(highcharter)
df <- gapminder %>% group_split(country)
countries <- df[1:10] %>% set_names(1:10)
ggplots_list <- countries %>% map(~ .x %>% ggplot(aes(x = year, y = pop)) + geom_line())
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "slider_new",
label = "Projections Range",
width = '100%',
min = 1, max = 10,
value = 1
) ,
plotOutput('chart_1', height = '500px')
)
server <- function(input, output, session) {
output$chart_1 <- renderPlot({
ggplots_list[input$slider_new[1]]
})
}
shinyApp(ui, server)
The idea is to have a grid of charts as I increase the slider value.
Any help?
Try this
library(gapminder)
library(highcharter)
library(purrr)
df <- gapminder %>% group_split(country)
countries <- df[1:10] %>% set_names(1:10)
ggplots_list <- countries %>% map(~ .x %>% ggplot(aes(x = year, y = pop)) + geom_line())
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "slider_new",
label = "Projections Range",
width = '100%',
min = 1, max = 10,
value = 1
) ,
uiOutput("chart_1")
)
server <- function(input, output, session) {
lapply(1:10, function(i){
output[[paste0("plots",i)]] <- renderPlot({ ggplots_list[i] })
})
output$chart_1 <- renderUI({
n <- input$slider_new
lapply(1:n, function(i) plotOutput(paste0("plots",i), height=500))
})
}
shinyApp(ui, server)
I'm new in programming language especially R.
I have data frame and want to show top 3 of my data and sort from the biggest value using bar chart. I have tried some codes but failed to create proper chart. Here is my latest code :
library(shiny)
library(plotly)
my_data <- data.frame(x1 = c("a","b", "c","d","e","f","g","h"),
x2 = c(200, 200, 100,200,200,100,200,100),
x3 = c(100,400,500,50,100,300,100,50))
df1 <- my_data[order(my_data$x3),] #order by x3 value, to create rank
ui <- tabPanel("Test",
sidebarLayout(
sidebarPanel(
selectInput(inputId = "why",
label = "1. Select",
choices = df1$x2),
),
mainPanel(plotlyOutput("test"))
))
server <- function(input, output, session) {
output$test <- renderPlotly({
df2 <- df1 %>%
filter(x2 ==input$why) #filter by x2
p <-ggplot(df2,
aes(x = x1, y=x3)) +
geom_bar(stat = "identity")
fig <- ggplotly(p)
fig
})}
shinyApp(ui = ui, server = server)
the bar chart I created was not ordered correctly (based on x3 values), and I also only want to show top 3 of my data
To filter for the top 3 rows you could use dplyr::slice_max and to reorder your bars use e.g. reorder. Simply reordering the dataset will not work.
library(shiny)
library(dplyr)
library(plotly)
ui <- tabPanel(
"Test",
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "why",
label = "1. Select",
choices = unique(df1$x2),
selected = 200
),
),
mainPanel(plotlyOutput("test"))
)
)
server <- function(input, output, session) {
output$test <- renderPlotly({
df2 <- df1 %>%
filter(x2 == input$why) %>%
slice_max(x3, n = 3, with_ties = FALSE)
p <- ggplot(
df2,
aes(x = reorder(x1, -x3), y = x3)
) +
geom_bar(stat = "identity")
fig <- ggplotly(p)
fig
})
}
shinyApp(ui = ui, server = server)
#>
#> Listening on http://127.0.0.1:8022
I know the question is already answered, but I encourage you to keep your server function as small as possible and try to wrap long series of code into functions.
Here is an example of what I mean
library(tidyverse)
library(shiny)
library(plotly)
my_data <- data.frame(x1 = c("a","b", "c","d","e","f","g","h"),
x2 = c(200, 200, 100,200,200,100,200,100),
x3 = c(100,400,500,50,100,300,100,50))
df1 <- my_data[order(my_data$x3),] #order by x3 value, to create rank
myPlot <- function(data, input) {
df <- data |>
filter(x2 == input) #filter by x2
p <-ggplot(df, aes(x = reorder(x1, -x3), y=x3)) +
geom_bar(stat = "identity")
return(ggplotly(p))
}
ui <- tabPanel("Test",
sidebarLayout(
sidebarPanel(
selectInput(inputId = "why",
label = "1. Select",
choices = df1$x2),
),
mainPanel(plotlyOutput("test"))
))
server <- function(input, output, session) {
output$test <- renderPlotly({
myPlot(df1, input$why)
})
}
shinyApp(ui = ui, server = server)
I keep getting errors like Error in : object of type 'closure' is not subsettable or
'..1'. x Input '..1' must be of size 28 or 1, not size 0. I am trying to change the bar graph based on what options are selected or not in the checkbox.
I changed the column names for ease of use from where I got the data.
library(shiny)
library(dplyr)
library(plotly)
#dataset link: https://www.kaggle.com/mahirahmzh/starbucks-customer-retention-malaysia-survey?select=Starbucks+satisfactory+survey.csv
#c("Timestamp","Gender","age","currently","income","visit_freq","Enjoy","Time","Nearby","membership","freq_purchase","avg_spend","Ratevsother","rateprice","salesandpromotion","ambiance","wifi","service","meetup","heardaboutpromotions","continuepatronage")
data <-read.csv("Starbucks satisfactory survey.csv", header=TRUE)
Categorical.Variables <- c("visit_freq", "age", "income")
ui <- fluidPage(
sidebarPanel(
selectInput('category', choices = Categorical.Variables, label = 'Select filter options:'),
conditionalPanel(condition = "input.category != '-'",
uiOutput("select_category"))
)
)
server <- function(input, output) {
output$select_category <- renderUI({
choices <- as.list(unique(data[[input$category]]))
checkboxGroupInput('categorycheck', label = 'Select filter:',
choices = choices,selected = choices)
data2 <- reactive({
data %>%
group_by(gender,data[[input$category]], currently,membership) %>%
summarize(n = n(), .groups="drop") %>%
filter(data[[input$category]] %in% input$categorycheck) %>%
filter(membership == "Yes")})
renderPlotly({
data2 <- data2()
colnames(data2) <- c("gender","filtercategory","currently","membership","n")
plot_ly(data2, x = ~currently, y = ~n, type = "bar", color=~gender, colors="Dark2") %>%
layout(barmode = 'group')
})
})
}
shinyApp(ui, server)
You have several issues. You should close your renderUI prior to using input$categorycheck in the reactive object data2. In addition, columns names in the csv file are long. Once you define the column names of data the way you are analyzing, it will work. Try this
mydata <-read.csv("Starbucks satisfactory survey.csv", header=TRUE)
names(mydata)[1:10] <- c("Timestamp", "gender", "Age", "currently", "Income", "visit_freq","drink_freq","time_spent", "nearby","membership")
Categorical.Variables <- c("Age", "Income", "visit_freq")
ui <- fluidPage(
sidebarPanel(
selectInput('category', choices = Categorical.Variables, label = 'Select filter options:'),
#conditionalPanel(condition = "input.category != '-'",
uiOutput("select_category")
# )
),
mainPanel(plotlyOutput("myplot"),
DTOutput("t1")
)
)
server <- function(input, output) {
output$select_category <- renderUI({
req(input$category)
choices <- as.list(unique(mydata[[input$category]]))
checkboxGroupInput('categorycheck', label = 'Select filter:',
choices = choices,selected = choices)
})
data2 <- reactive({
req(input$category,input$categorycheck)
mydata %>%
group_by(gender,.data[[input$category]], currently,membership) %>%
dplyr::summarize(n = n(), .groups="drop") %>%
filter(.data[[input$category]] %in% input$categorycheck) %>%
filter(membership == "Yes")})
output$t1 <- renderDT(data2())
output$myplot <- renderPlotly({
req(data2())
data2 <- data2()
colnames(data2) <- c("gender","filtercategory","currently","membership","n")
plot_ly(data2, x = ~currently, y = ~n, type = "bar", color=~gender, colors="Dark2") %>%
layout(barmode = 'group')
})
}
shinyApp(ui, server)
\
I'm a really beginner in R Shiny.
I have a similar problem as at the link below.
multiple group_by in shiny app
Instead of making a table which worked out/I managed by following the instructions in the link above.
I would like to make a plot, preferably with hchart. In which i would to switch the information because of the group by. The difficult part / or the thing that doesn't work is putting the group_by on the x-axis.
## hier de tabel versie
df2 <- readRDS("Data.rds")
library(shiny)
library(DT)
library(dplyr)
ui <- fluidPage(
titlePanel("Dashboard"),
sidebarLayout(
sidebarPanel(
uiOutput("groups")
),
mainPanel(
DT::dataTableOutput("summary")
)
)
)
server <- function(input, output) {
mydata <- reactive({
data <- df2
data
})
output$groups <- renderUI({
df <- mydata()
selectInput(inputId = "grouper", label = "Group variable", choices = c("L","Lt","Lp"), selected = "L")
})
summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!!rlang::syms(input$grouper)) %>%
dplyr::summarise(aantal = n()) %>%
dplyr::arrange(desc(aantal))
})
output$summary <- DT::renderDataTable({
DT::datatable(summary_data())
})
}
shinyApp(ui, server)
The above code works, but i tried to make a plot like this:
df2 <- readRDS("Data.rds")
library(shiny)
library(highcharter)
library(dplyr)
ui <- fluidPage(
titlePanel("Dashboard"),
sidebarLayout(
sidebarPanel(
uiOutput("groups")
),
mainPanel(
highchartOutput("plotje")
)
)
)
server <- function(input, output) {
mydata <- reactive({
data <- df2
data
})
output$groups <- renderUI({
df <- mydata()
selectInput(inputId = "grouper", label = "Group variable", choices = c("L","Lt","Lp"), selected = "L")
})
summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!!rlang::syms(input$grouper)) %>%
dplyr::summarise(aantal = n()) %>%
dplyr::arrange(desc(aantal))
})
output$plotje <- renderHighchart({
data <- summary_data()
hchart(data, "column", hcaes(x = "grouper" , y = aantal)) # --> de plot zelf komt in het output deel van de UI
})
}
shinyApp(ui, server)
Could someone help me out?!
Thanks in advance!
Kind regards,
Steffie
You have the grouper column in the input$grouper var.
It's just a matter of unquoting it.
The line hchart(data, "column", hcaes(x = "grouper" , y = aantal)) should be:
hchart(data, "column", hcaes(x = !!input$grouper , y = aantal))
Full example (with iris data as you didn't provide an example of your own data):
library(shiny)
library(DT)
library(highcharter)
library(dplyr)
ui <- fluidPage(titlePanel("Dashboard"),
sidebarLayout(
sidebarPanel(uiOutput("groups")),
mainPanel(DT::dataTableOutput("summary"),
highchartOutput("plot"))
))
server <- function(input, output) {
mydata <- reactive({
iris
})
output$groups <- renderUI({
df <- mydata()
selectInput(
inputId = "grouper",
label = "Group variable",
choices = c("Petal.Length", "Species"),
selected = "Species"
)
})
summary_data <- reactive({
req(input$grouper)
mydata() %>%
dplyr::group_by(!!!rlang::syms(input$grouper)) %>%
dplyr::summarise(aantal = n()) %>%
dplyr::arrange(desc(aantal))
})
output$summary <- DT::renderDataTable({
DT::datatable(summary_data())
})
output$plot <- renderHighchart({
req(input$grouper)
data <- summary_data()
hchart(data, "column", hcaes(x = !!input$grouper, y = aantal))
})
}
shinyApp(ui, server)
I am trying to create a shiny app where depending on the dataset, ggvis will create a scatter plot. The app works fine at the beginning. But if I try to change the dataset to mtcars, shiny just disappears.
My ui.R -
library(ggvis)
library(shiny)
th.dat <<- rock
shinyUI(fluidPage(
titlePanel("Reactivity"),
sidebarLayout(
sidebarPanel(
selectInput("dataset", "Choose a dataset:",
choices = c("rock", "mtcars")),
selectInput("xvar", "Choose x", choices = names(th.dat), selected = names(th.dat)[1]),
selectInput("yvar", "Choose y", choices = names(th.dat), selected = names(th.dat)[2]),
selectInput("idvar", "Choose id", choices = names(th.dat), selected = names(th.dat)[3])
),
mainPanel(
ggvisOutput("yup")
)
)
))
server.R -
library(ggvis)
library(shiny)
library(datasets)
shinyServer(function(input, output, session) {
datasetInput <- reactive({
switch(input$dataset,
"rock" = rock,
"mtcars" = mtcars)
})
obs <- observe({
input$dataset
th.dat <<- datasetInput()
s_options <- list()
s_options <- colnames(th.dat)
updateSelectInput(session, "xvar",
choices = s_options,
selected = s_options[[1]]
)
updateSelectInput(session, "yvar",
choices = s_options,
selected = s_options[[2]]
)
updateSelectInput(session, "idvar",
choices = s_options,
selected = s_options[[3]]
)
})
xvarInput <- reactive({
input$dataset
input$xvar
print("inside x reactive," )
print(input$xvar)
xvar <- input$xvar
})
yvarInput <- reactive({
input$dataset
input$yvar
print("inside y reactive,")
print(input$yvar)
yvar <- input$yvar
})
dat <- reactive({
dset <- datasetInput()
xvar <- xvarInput()
# print(xvar)
yvar <- yvarInput()
# print(yvar)
x <- dset[, xvar]
y <- dset[,yvar]
df <- data.frame(x = x, y = y)
})
dat %>%
ggvis(~x, ~y) %>%
layer_points() %>%
bind_shiny("yup")
})
I have tried many ways, but still stuck. Any help will be greatly appreciated.
I left some pointers in the comments but it seems that ggvis evaluates everything quite early so there is a need for some test cases.
rm(list = ls())
library(shiny)
library(ggvis)
ui <- fluidPage(
titlePanel("Reactivity"),
sidebarPanel(
selectInput("dataset", "Choose a dataset:", choices = c("rock", "mtcars")),
uiOutput("xvar2"),uiOutput("yvar2"),uiOutput("idvar2")),
mainPanel(ggvisOutput("yup"))
)
server <- (function(input, output, session) {
dataSource <- reactive({switch(input$dataset,"rock" = rock,"mtcars" = mtcars)})
# Dynamically create the selectInput
output$xvar2 <- renderUI({selectInput("xvar", "Choose x",choices = names(dataSource()), selected = names(dataSource())[1])})
output$yvar2 <- renderUI({selectInput("yvar", "Choose y",choices = names(dataSource()), selected = names(dataSource())[2])})
output$idvar2 <- renderUI({selectInput("idvar", "Choose id",choices = names(dataSource()), selected = names(dataSource())[3])})
my_subset_data <- reactive({
# Here check if the column names correspond to the dataset
if(any(input$xvar %in% names(dataSource())) & any(input$yvar %in% names(dataSource())))
{
df <- subset(dataSource(), select = c(input$xvar, input$yvar))
names(df) <- c("x","y")
return(df)
}
})
observe({
test <- my_subset_data()
# Test for null as ggvis will evaluate this way earlier when the my_subset_data is NULL
if(!is.null(test)){
test %>% ggvis(~x, ~y) %>% layer_points() %>% bind_shiny("yup")
}
})
})
shinyApp(ui = ui, server = server)
Output 1 for rocks
Output 2 for mtcars