I'm trying to use some reactive elements from predefined function and call that data from a module to generate plots, but data is not getting updated upon selection. I've also tried to call the function inside reactive() and call that from the module, but still same result. My approach is below:
library(shiny)
library(shinyWidgets)
library(highcharter)
library(data.table)
library(dplyr)
employement_type_count <- function(
data,
category,
...
){
data[employee_category %in% category, .(count = .N), by = employee_category]
}
pie_chart_ui <- function(id) {
ns <- NS(id)
highchartOutput(ns("pie"))
}
pie_chart_server <- function(
id,
data,
var_x = names(data)[1],
var_y = names(data)[2],
lab_x = names(data)[1],
lab_y = names(data)[2],
tooltip_name = names(data)[2],
export_title = NA
) {
moduleServer(
id,
function(input, output, session) {
output$pie <- renderHighchart({
data %>%
hchart(
'pie',
hcaes_(x = var_x, y = var_y),
name = tooltip_name
) %>%
hc_xAxis(title = list(text = lab_x)) %>%
hc_yAxis(title = list(text = lab_y)) %>%
hc_plotOptions(
pie = list(
allowPointSelect = TRUE,
cursor = 'pointer',
dataLabels = list(
enabled = TRUE,
format = '<b>{point.name}</b>: {point.percentage:.1f}%',
style = list(
color = "(Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'"
)
)
)
) %>%
hc_exporting(
enabled = TRUE,
buttons = list(
contextButton = list(
align = 'right'
)
),
chartOptions = list(
title = list(
text = export_title
)
)
)
})
}
)
}
ui <- fluidPage(
sidebarPanel(
pickerInput(
"employee_type",
"Employee Type",
choices = c("Regular", "Project", "Service", "Part-Time"),
selected = c("Regular", "Project", "Service", "Part-Time"),
multiple = TRUE
)
),
mainPanel(
pie_chart_ui("employee_category")
)
)
server <- function(input, output, session){
# data_common <- fread("data_common.csv")
data_common <- data.table(
id = 1:26,
employee_name = LETTERS,
gender_type = rep(c("Male", "Female"), each = 13),
employee_category = c("Regular", "Project", rep(c("Regular", "Project", "Service", "Part-Time"), times = 6))
)
pie_chart_server(
"employee_category",
employement_type_count(
data_common,
input$employee_type
)
)
}
shinyApp(ui, server)
Note that, data should be imported from server, instead of global, as it is constantly getting updated.
One way to do it is shown below.
library(shiny)
library(shinyWidgets)
library(highcharter)
library(data.table)
library(dplyr)
df1 <- data.table(
id = 1:26,
employee_name = LETTERS,
gender_type = rep(c("Male", "Female"), each = 13),
employee_category = c("Regular", "Project", rep(c("Regular", "Project", "Service", "Part-Time"), times = 6))
)
employement_type_count <- function(
data,
category,
...
){
data <- data()
if (is.null(category())) {df <- data
}else df <- data[employee_category %in% category(), .(count = .N), by = employee_category]
return(df)
}
pie_chart_ui <- function(id) {
ns <- NS(id)
highchartOutput(ns("pie"))
}
pie_chart_server <- function(
id,
data,
var_x = names(data)[1],
var_y = names(data)[2],
lab_x = names(data)[1],
lab_y = names(data)[2],
tooltip_name = names(data)[2],
export_title = NA
) {
moduleServer(
id,
function(input, output, session) {
output$pie <- renderHighchart({
data %>%
hchart(
'pie',
hcaes_(x = var_x, y = var_y),
name = tooltip_name
) %>%
hc_xAxis(title = list(text = lab_x)) %>%
hc_yAxis(title = list(text = lab_y)) %>%
hc_plotOptions(
pie = list(
allowPointSelect = TRUE,
cursor = 'pointer',
dataLabels = list(
enabled = TRUE,
format = '<b>{point.name}</b>: {point.percentage:.1f}%',
style = list(
color = "(Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'"
)
)
)
) %>%
hc_exporting(
enabled = TRUE,
buttons = list(
contextButton = list(
align = 'right'
)
),
chartOptions = list(
title = list(
text = export_title
)
)
)
})
}
)
}
ui <- fluidPage(
sidebarPanel(
pickerInput(
"employee_type",
"Employee Type",
choices = c("Regular", "Project", "Service", "Part-Time"),
selected = c("Regular", "Project", "Service", "Part-Time"),
multiple = TRUE
)
),
mainPanel(
pie_chart_ui("employee_category")
)
)
server <- function(input, output, session){
# data_common <- fread("data_common.csv")
data_common <- reactive(df1)
employee <- reactive(input$employee_type)
observe({
mydata <- employement_type_count(
data_common,
employee
)
pie_chart_server(
"employee_category",
mydata
)
})
}
shinyApp(ui, server)
Related
I'm working on a table rendered with rhandsontable that uses dropdown menus for user inputs into the table. My dropdown approach is based on guidance provided in post Is there a way to have different dropdown options for different rows in an rhandsontable?. I'm trying to add a feature where the user clicks on an actionButton() in order to add a column to the table and sequentially numbers the header for the added column, with the dropdowns included in the added column. The below code almost works, except that added columns don't have the required dropdowns. What am I doing wrong here?
Code:
library(shiny)
library(rhandsontable)
ui <- fluidPage(br(),
mainPanel(
actionButton("add", "Add column"),br(),br(),
rHandsontableOutput("Tbl")
)
)
server <- function(input, output) {
DF <- reactiveVal(
data.frame(
'Series 1' = NA_character_,
stringsAsFactors = FALSE,
row.names = c("Select option"),
check.names = FALSE
)
)
observeEvent(input$Tbl,{DF(hot_to_r(input$Tbl))})
output$Tbl <- renderRHandsontable({
select_option <- c(NA_character_, "dog", "cat") # defines the dropdown options
tmp <- rhandsontable(DF(), rowHeaderWidth = 200, selectCallback = TRUE, height = 300) %>%
hot_cols(colWidths = 100) %>%
hot_col("Series 1",
allowInvalid = FALSE,
type = "dropdown",
source = NA_character_,
readOnly = TRUE
)
tmp <- hot_col(tmp,
col = "Series 1",
allowInvalid = FALSE,
type = "dropdown",
source = select_option
) %>%
hot_cell(row = input$Tbl_select$select$r, col = "Series 1", readOnly = FALSE)
tmp
})
observeEvent(input$add, {
select_option <- c(NA_character_, "dog", "cat") # defines the dropdown options
newCol <- data.frame('Series 1' = NA_character_,stringsAsFactors = FALSE)
names(newCol) <- paste("Series", ncol(hot_to_r(input$Tbl)) + 1)
DF(cbind(DF(), newCol))
})
}
shinyApp(ui = ui, server = server)
You need to apply hot_col(type = "dropdown") on every column of the reactive data.frame (col = names(DF())) not only on the first col = "Series 1":
library(shiny)
library(rhandsontable)
ui <- fluidPage(br(),
mainPanel(
actionButton("add", "Add column"),br(),br(),
rHandsontableOutput("Tbl")
)
)
server <- function(input, output) {
DF <- reactiveVal(
data.frame(
'Series 1' = NA_character_,
stringsAsFactors = FALSE,
row.names = c("Select option"),
check.names = FALSE
)
)
observeEvent(input$Tbl,{DF(hot_to_r(input$Tbl))})
output$Tbl <- renderRHandsontable({
select_option <- c(NA_character_, "dog", "cat") # defines the dropdown options
rhandsontable(DF(), rowHeaderWidth = 200, selectCallback = TRUE, height = 300) %>%
hot_cols(colWidths = 100) %>%
hot_col(col = names(DF()),
allowInvalid = FALSE,
type = "dropdown",
source = select_option
) %>%
hot_cell(row = input$Tbl_select$select$r, col = "Series 1", readOnly = FALSE)
})
observeEvent(input$add, {
select_option <- c(NA_character_, "dog", "cat") # defines the dropdown options
newCol <- data.frame('Series 1' = NA_character_,stringsAsFactors = FALSE)
names(newCol) <- paste("Series", ncol(hot_to_r(input$Tbl)) + 1)
DF(cbind(DF(), newCol))
})
}
shinyApp(ui = ui, server = server)
Following up on ismirsehregal's solution for column addition, the below offers both column addition and deletion via actionButton():
library(shiny)
library(rhandsontable)
ui <- fluidPage(br(),
mainPanel(
actionButton("add", "Add column"),br(),br(),
actionButton("delSeries","Select series below to delete"),
uiOutput("delSeries2"),
rHandsontableOutput("Tbl")
)
)
server <- function(input, output) {
DF <- reactiveVal(
data.frame(
'Series 1' = NA_character_,
stringsAsFactors = FALSE,
row.names = c("Select option"),
check.names = FALSE
)
)
observeEvent(input$Tbl,{DF(hot_to_r(input$Tbl))})
output$Tbl <- renderRHandsontable({
select_option <- c(NA_character_, "dog", "cat") # defines the dropdown options
tmp <- rhandsontable(DF(), rowHeaderWidth = 200, selectCallback = TRUE, height = 300) %>%
hot_cols(colWidths = 100) %>%
hot_col("Series 1",
allowInvalid = FALSE,
type = "dropdown",
source = NA_character_,
readOnly = TRUE
)
tmp <- hot_col(tmp,
col = names(DF()), # adding this is what fixed it
allowInvalid = FALSE,
type = "dropdown",
source = select_option
) %>%
hot_cell(row = input$Tbl_select$select$r, col = "Series 1", readOnly = FALSE)
tmp
})
observeEvent(input$add, {
newCol <- data.frame('Series 1' = NA_character_,stringsAsFactors = FALSE)
names(newCol) <- paste("Series", ncol(hot_to_r(input$Tbl)) + 1)
DF(cbind(DF(), newCol))
})
observeEvent(input$delSeries3, {
tmp <- DF()
delCol <- input$delSeries3
tmp <- tmp[ , !(names(tmp) %in% delCol), drop = FALSE]
newNames <- sprintf("Series %d",seq(1:ncol(tmp)))
names(tmp) <- newNames
DF(tmp)
})
output$delSeries2 <-
renderUI(
selectInput("delSeries3",
label = NULL,
choices = colnames(hot_to_r(input$Tbl)),
selected = "",
multiple = TRUE,
width = '110px')
)
}
shinyApp(ui = ui, server = server)
i want to use input$dateRange[1] and input$dateRange[1] in a function that request data from a database in my company .the function i am using belongs to a package that belongs to my firm but it is that complicated it is built over sql and c (stuff like that).when i launch my app i get the following error :
Warning: Error in wmq_find: object 'input' not found
50: wmq_find
Error in wmq_find(progb = "FCM", from = input$dateRange[1], to = input$dateRange[2], :
object 'input' not found
below is a litte bite of code used in the UI und then you can find a chunk of code used ih the server:
sidebar = dashboardSidebar(
collapsed = FALSE,
width = 290,
sidebarMenu(
menuItem("Summary",tabName = "Summary") ,
dateRangeInput('dateRange',
label = 'Filter by date',
start = "2021-09-14" , end = "2021-09-21"
)
and then:
myd1<- wmq_find(progb = "FCM",from = input$dateRange[1] ,to= input$dateRange[2],verbose = T, dbLocation = "erfurt", outMode = "outh",maptype = "cmap")
New code:
myda1<- eventReactive(input$update, {
# paste("From:", input$dateRange[1], "to:", input$dateRange[2])
wmq_find(
progb = "FCM",
from = paste(input$dateRange[1]),
to = paste(input$dateRange[2]),
verbose = T,
dbLocation = "erfurt",
outMode = "outh",
maptype = "cmap"
)})
mergeddata<-reactive({
myd1<-myda1()[ !duplicated(myda1()[, c("wafer_Id", "date","time")], fromLast=T),]
myd1<-myd1[,c(4,5,7,9,11,18,20,21)]
myd1$Lot_Wf <- paste(myd1$lot_Id, myd1$wafer_Id,sep="/")
colnames(myd1)<-c("Lot","Wafer","M_Datum","Messprogramm","Device","Total","Pass","Yield","Lot/Wf")
myd1$M_Datum<-as.Date(myd1$M_Datum,format="%d.%m.%y")
myd1<-unique(myd1)
myd1$Device<-gsub(" ","",myd1$Device)
myd1$Lot<-gsub(" ","",myd1$Lot)
myd1$Yield<-suppressWarnings(as.numeric(myd1$Yield))
myd1$Messprogramm<-gsub(" ","",myd1$Messprogramm)
myd1<-myd1[myd1$Messprogramm=="FCM_ERF",]
mergeddata<-merge(myd1,mydonee,by="Device")
#dte[,4]<-strftime(dte[,4], format = '%Y-%m-%d %R')
# dte[,4]<-as.Date(substr(dte[,4],0,10),"%Y-%m-%d")
colnames(mergeddata)<-gsub(" ","_",colnames( mergeddata))
colnames( mergeddata)<-gsub("-","_",colnames( mergeddata))
return( mergeddata)
})
res_mod <- callModule(
module = selectizeGroupServer,
id = "m",
data = mergeddata,
vars = c("Device","MEMS_flag","Process_Family","Local_Process_id","Customer_Name"),
inline=FALSE
)
output$table <- renderDataTable({
input$update
dato<-res_mod()
return(dato) },
options = list(scrollX = TRUE))
Please check the following:
library(shiny)
library(shinydashboard)
library(DT)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(
collapsed = FALSE,
width = 290,
sidebarMenu(
menuItem("Summary", tabName = "Summary"),
dateRangeInput(
'dateRange',
label = 'Filter by date',
start = "2021-09-14",
end = "2021-09-21"
),
actionButton(
inputId = "update",
label = "Update Data",
icon = icon("arrows-rotate"),
width = "260px"
)
)
),
dashboardBody(DTOutput("my_table"))
)
server <- function(input, output, session) {
dummyDF <- data.frame(date = seq(from = as.Date("2021-09-14"), to = as.Date("2021-09-21"), "days"), value = 1:8)
myd1 <- eventReactive(input$update, {
dummyDF[dummyDF$date >= min(as.Date(input$dateRange)) & dummyDF$date <= max(as.Date(input$dateRange)),]
# wmq_find(
# progb = "FCM",
# from = input$dateRange[1],
# to = input$dateRange[2],
# verbose = T,
# dbLocation = "erfurt",
# outMode = "outh",
# maptype = "cmap"
# )
})
output$my_table <- renderDT({
myd1()
}, server = FALSE)
}
shinyApp(ui, server)
I am putting together an Shiny app to allow users to upload an area of interest (AOI), and calculate the amount of overlap with an administrative boundary (WMU). Everything is working as desired, except that my picker input options do not update. The picker input works, but I would like the choices to only include the WMU that overlap the AOI instead of all possible WMU. I can calculate the WMU ID that should populate the list, shown in the "TEST_TEXT"output below the map frame, but cannot successfully update the pickerInput. This kmz will overlap the several WMU that are loaded at the beginning of the script included below:
library(shiny)
library(sf)
library(tidyverse)
library(bcdata)
library(shinyjs)
library(leaflet)
library(mapview)
library(DT)
library(pals)
library(shinyWidgets)
library(shinymanager)
WMU_DATA <-
bcdc_get_data("wildlife-management-units") %>% st_transform(4326) %>% mutate(Total.WMU.HA =
as.numeric(st_area(.)) / 10000)
##### UI #####
ui <- fluidPage(
tags$head(tags$style(
HTML(
".shiny-notification {
height: 100px;
width: 400px;
position:fixed;
top: calc(25% - 50px);;
left: calc(50% - 200px);;
}
"
)
)),
# Application title
titlePanel("Calculate Overlap With WMU"),
# Inputs
sidebarLayout(
sidebarPanel(
width = 3,
textInput(
inputId = "AOI_NAME",
label = "AOI Name",
value = NULL
),
HTML("<br><br>"),
fileInput(
inputId = "KMZ",
label = "Choose KMZ",
multiple = FALSE,
accept = c('.kmz')
),
h3("or"),
HTML("<br><br>"),
fileInput(
inputId = "SHAPEFILE",
label = "Choose shapefile",
multiple = TRUE,
accept = c('.shp', '.dbf', '.sbn', '.sbx', '.shx', '.prj', '.xml')
),
pickerInput(
inputId = "WMU_FILTER",
label = "Filter Overlapping WMU",
choices = unique(WMU_DATA$WILDLIFE_MGMT_UNIT_ID),
selected = unique(WMU_DATA$WILDLIFE_MGMT_UNIT_ID),
multiple = TRUE,
options = list(`actions-box` = TRUE)
),
HTML("<br><br>")
),
# Display OUtputs
mainPanel(
width = 9,
leafletOutput("OVERLAP_MAP", height = 750),
h3(textOutput("TEST_TEXT")),
DTOutput("AOI_OVERLAP_TABLE")
)
)
)
######server#####
server <- function(input, output, session) {
####reactive data
AOI <-
reactive({
if (is.null(input$SHAPEFILE) & !is.null(input$KMZ)) {
st_read(unzip(input$KMZ$datapath)) %>%
st_zm(drop = T) %>%
mutate(AOI_NAME = input$AOI_NAME) %>%
st_transform(4326) %>%
select(-Name)
}
else if (!is.null(input$SHAPEFILE) & is.null(input$KMZ)) {
SHAPEFILE()
}
else{
return(NULL)
}
})
WMU_OVERLAP <- reactive({
st_filter(WMU_DATA, AOI())
})
AOI_WMU_INTERSECT <-
reactive({
st_intersection(AOI(), WMU_OVERLAP()) %>%
mutate(`HA of Overlap` = round(as.numeric(st_area(.)) / 10000, 0)) %>%
mutate(`Percent of WMU` = round(`HA of Overlap` / `Total.WMU.HA` *
100, 2))
})
observeEvent(AOI_WMU_INTERSECT
,
{
updatePickerInput(
session,
"WMU_FILTER",
choices = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID),
selected = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID)
)
},
ignoreInit = TRUE,
ignoreNULL = TRUE)
###outputs
output$OVERLAP_MAP <-
renderLeaflet({
withProgress(message = "Calcualting Overlap", detail = "Should be done soon", {
AOI_SPATIAL <- AOI() %>% mutate(AOI_NAME = input$AOI_NAME)
WMU <-
WMU_OVERLAP() %>% filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
Overlap <-
AOI_WMU_INTERSECT() %>% filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
MAP <-
mapview(
Overlap,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
map.types = c("Esri.WorldTopoMap", "Esri.WorldImagery"),
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
))
) +
mapview(
WMU,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
lwd = 3,
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
)),
hide = TRUE
) +
mapview(AOI_SPATIAL,
label = "AOI_NAME",
col.regions = "red")
MAP#map %>%
setView(st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 1],
st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 2],
zoom = 9)
})
})
output$AOI_OVERLAP_TABLE <-
renderDT({
AOI_OVERLAP_TABLE <- AOI_WMU_INTERSECT() %>%
st_drop_geometry()
AOI_OVERLAP_TABLE
}, filter = "top", extensions = c("FixedHeader", "Buttons"),
options = list(
pageLength = 100,
fixedHeader = TRUE,
dom = "Bfrtip",
buttons = c('colvis', 'copy', 'excel', 'csv')
))
output$TEST_TEXT <-
renderText(unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID))
}
# Run the application
shinyApp(ui = ui, server = server)
Putting some req() and changing observeEvent() to observe() makes it work. Try this
######server#####
server <- function(input, output, session) {
####reactive data
AOI <-
reactive({
if (is.null(input$SHAPEFILE) & !is.null(input$KMZ)) {
st_read(unzip(input$KMZ$datapath)) %>%
st_zm(drop = T) %>%
mutate(AOI_NAME = input$AOI_NAME) %>%
st_transform(4326) %>%
select(-Name)
}
else if (!is.null(input$SHAPEFILE) & is.null(input$KMZ)) {
SHAPEFILE()
}
else{
return(NULL)
}
})
WMU_OVERLAP <- reactive({
req(AOI())
st_filter(WMU_DATA, AOI())
})
AOI_WMU_INTERSECT <-
reactive({
req(AOI(), WMU_OVERLAP())
st_intersection(AOI(), WMU_OVERLAP()) %>%
dplyr::mutate(`HA of Overlap` = round(as.numeric(st_area(.)) / 10000, 0)) %>%
dplyr::mutate(`Percent of WMU` = round(`HA of Overlap` / `Total.WMU.HA` *100, 2))
})
observe({updatePickerInput(
session,
"WMU_FILTER",
choices = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID),
selected = unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID)
)
} )#, ignoreInit = TRUE, ignoreNULL = TRUE)
###outputs
output$OVERLAP_MAP <-
renderLeaflet({
req(AOI_WMU_INTERSECT())
withProgress(message = "Calcualting Overlap", detail = "Should be done soon", {
AOI_SPATIAL <- AOI() %>% dplyr::mutate(AOI_NAME = input$AOI_NAME)
WMU <-
WMU_OVERLAP() %>% dplyr::filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
Overlap <-
AOI_WMU_INTERSECT() %>% dplyr::filter(WILDLIFE_MGMT_UNIT_ID %in% input$WMU_FILTER)
MAP <-
mapview(
Overlap,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
map.types = c("Esri.WorldTopoMap", "Esri.WorldImagery"),
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
))
) +
mapview(
WMU,
zcol = "WILDLIFE_MGMT_UNIT_ID",
alpha.regions = 0.2,
lwd = 3,
col.regions = alphabet(nlevels(
as.factor(WMU$WILDLIFE_MGMT_UNIT_ID)
)),
hide = TRUE
) +
mapview(AOI_SPATIAL,
label = "AOI_NAME",
col.regions = "red")
MAP#map %>%
setView(st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 1],
st_coordinates(st_centroid(st_as_sfc(
st_bbox(AOI_SPATIAL)
)))[, 2],
zoom = 9)
})
})
output$AOI_OVERLAP_TABLE <-
renderDT({
AOI_OVERLAP_TABLE <- AOI_WMU_INTERSECT() %>% st_drop_geometry()
AOI_OVERLAP_TABLE
}, filter = "top", extensions = c("FixedHeader", "Buttons"),
options = list(
pageLength = 100,
fixedHeader = TRUE,
dom = "Bfrtip",
buttons = c('colvis', 'copy', 'excel', 'csv')
))
output$TEST_TEXT <- renderText(unique(AOI_WMU_INTERSECT()$WILDLIFE_MGMT_UNIT_ID))
}
I created an application in Shiny where I would like to choose multiple items from the drop-down menu. Unfortunately, I don't know how to make items on the list reduce after a given menu selection. By which all lines merge into a whole. what should I add in the code so that each model is a separate line. Below I put a picture with charts.
My code:
library(shiny)
library(plotly)
library(readxl)
library(shinyWidgets)
library(shinydashboard)
library(shinyjs)
library(DT)
df1 <- data.frame(Month = rep(month.abb[1:12],10,replace = TRUE), Model = paste0('Ferrari ', rep(LETTERS[1:10], each = 12)),
Value = sample(c(0:300),120, replace = T),
Car = rep('Ferrari', 10,each = 12), Year = rep(2019:2020, each = 60),Country = rep(c("USA","DE"), each = 12, times = 5), stringsAsFactors = F)
df2 <- data.frame(Month = rep(month.abb[1:12],10,replace = TRUE), Model = paste0('Porsche ', rep(LETTERS[1:10], each = 12)),
Value = sample(c(0:300),120, replace = T),
Car = rep('Porsche', 10,each = 12), Year = rep(2019:2020, each = 60), Country = rep(c("USA","DE"), each = 12, times = 5),stringsAsFactors = F)
data <-rbind(df1, df2)
ui <- fluidPage(
titlePanel("Test"),
sidebarLayout(
sidebarPanel( width = 3,
uiOutput("category1"),
uiOutput("category2"),
uiOutput("category3"),
uiOutput("category4")),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Plot", plotlyOutput("plot", height = 550,width = 1000))
)
)
)
)
server <- function(input, output,session) {
output$category1 <- renderUI({
selectInput('cat1', 'Choose year:', multiple = T, selected = NULL, choices = sort(as.numeric(unique(data$Year))))
})
df_subset <- eventReactive(input$cat1,{
if(input$cat1=="All") {df_subset <- data}
else{df_subset <- data[data$Year == input$cat1,]}
})
df_subset1 <- reactive({
if(is.null(input$cat2)){df_subset()} else {df_subset()[df_subset()$Country %in% input$cat2,]}
})
output$category2 <- renderUI({
selectInput('cat2', 'Choose country:', choices = sort(as.character(unique(df_subset()$Country))), multiple = T, selected = NULL)
})
df_subset2 <- reactive({
if(is.null(input$cat3)){df_subset1()} else {df_subset1()[df_subset1()$Car %in% input$cat3,]}
})
output$category3 <- renderUI({
selectInput('cat3', 'Choose car:', choices = sort(as.character(unique(df_subset1()$Car))), multiple = F, selected = NULL)
})
df_subset3 <- reactive({
if(is.null(input$cat4)){df_subset2()} else {df_subset2()[df_subset2()$Model %in% input$cat4,]}
})
output$category4 <- renderUI({
pickerInput('cat4', 'Choose model:', choices = sort(as.character(unique(df_subset2()$Model))), multiple = TRUE, selected = NULL)
})
output$plot <- renderPlotly({
xform <- list(categoryorder = "array",
categoryarray = df_subset3()$Month,
title = " ",
nticks=12)
plot_ly(data=df_subset3(), x=~Month, y = ~Value, type = 'scatter', mode = 'lines', name = 'Value') %>%
layout(title = " ",xaxis = xform) %>%
layout(legend = list(orientation = 'h', xanchor = "center", y=1.1, x=0.5))
})
}
shinyApp(ui, server)
To display each model as a separate line on the plot, you can assign the Model column of your dataset to the color parameter of plot_ly this way:
plot_ly( data = df_subset3(), x = ~Month, y = ~Value, color = ~Model, ...)
I have been messing with making a shiny app and I feel as though i am doing everything in the correct manner to get the table to render but no luck. In my app you should you upload an csv and then go to the data frame tab. I have tried many small changes but nothing seems to work. Id imagine this has something to do with the server section but i cant see it.
R ui:
library(readxl)
library(plyr)
library(dplyr)
library(plotly)
library(readr)
library(RColorBrewer)
library(data.table)
library(shiny)
library(shinydashboard)
library(shinythemes)
library(leaflet)
library(DT)
library(xtable)
ui <- fluidPage(theme = shinytheme("slate"), mainPanel(
navbarPage(
"Permian Plots", collapsible = TRUE, fluid = TRUE,
navbarMenu(
"County Plot",
tabPanel(
sidebarPanel( fileInput(
'file1',
'Choose CSV File',
accept = c('text/csv', 'text/comma-separated-values,text/plain', '.csv')
),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
# App buttons comma and quote
radioButtons('sep', 'Separator',
c(
Comma = ',',
Semicolon = ';',
Tab = '\t'
), ','),
radioButtons(
'quote',
'Quote',
c(
None = '',
'Double Quote' = '"',
'Single Quote' = "'"
),
'"'
))
),
tabPanel("Data Frame",
fluidRow(box(DT::dataTableOutput("contents")))),
tabPanel("County Plot", plotlyOutput(
"plotMap", height = 1200, width = 1200
),
actionButton("btn", "Plot")
)
)
)
)
)
Server:
server <- function(input, output, session) {
options(shiny.maxRequestSize = 200*1024^2)
dsnames <- c()
data_set <- reactive({
inFile <- input$file1
if (is.null(inFile)){
return()
}
data_set <- read.csv(
inFile$datapath,
header = input$header,
sep = input$sep,
quote = input$quote
)
})
output$contents <- DT::renderDataTable({
withProgress(message = 'loading...', value = 0.1, {
datatable(data_set(),
options = list(
"pageLength" = 40))
extensions = 'Responsive'
setProgress(1)
})
})
output$choose_dataset <- renderUI({
selectInput("dataset", "Data set", as.list(data_sets))
})
observeEvent(
input$btn,
{
output$plotMap <- renderPlotly({withProgress(message = 'Plotting...', value = 0.1,{
plot <- Plots(data_set(),
"Martin County",
"~/Work/permin/martin county/martin data/f1.csv",
"~/Work/permin/BestMartinPlotSat.html",
32.1511, -101.5715)
setProgress(1)
})
})
}
)
}
shinyApp(ui = ui, server = server)
Function:
Should not be the problem causer in this.
Plots <- function(df, C_name, PathCSV, PathWidg, Lat, Lon){
f1 <- df
f1$Date <- as.POSIXct(f1$Date)
f1$year <- format(as.POSIXct(f1$Date,format="%y-%m-%d"), "%y")
f1$month <- format(as.POSIXct(f1$Date,format="%y-%m-%d"), "%m")
f1$Cell <- as.factor(f1$Cell)
z <- ddply(f1, c("year", "month", "Cell"), summarise,
yearMonth_Max_sum = max(`Cell Sum (Norm)`))
f1 <- inner_join(f1,z, by = c("year", "month", "Cell"))
f1$Changed <- as.numeric(as.factor(f1$Changed))
f1$Changed[f1$Changed == 1] <- 0
f1$Changed[f1$Changed == 2] <- 1
z <- ddply(f1, c("year", "month", "Cell"), summarise,
ChangedX = max(Changed))
f1 <- inner_join(f1,z, by = c("year", "month", "Cell"))
f1$MY <- paste(f1$year, f1$month, sep = "-")
#preapring data for plotly
q <- matrix(quantile(f1$StdDev))
f1$qunat <- NA
up <- matrix(quantile(f1$StdDev, probs = .95))
up
f1$qunat <- ifelse((f1$StdDev > q[4:4,1]) & (f1$StdDev < up[1,1]), 1, 0)
z <- group_by(f1, Cell) %>%
summarize(Median_Cell = median(`Cell Sum (Norm)`, na.rm = FALSE))
f1 <- inner_join(f1,z, by = c("Cell"))
quantile(round(f1$Median_Cell))
f1$NewMedian <- NA
f1$NewMedian[f1$Median_Cell > 4000] <- 0
f1$NewMedian[f1$Median_Cell <= 4000] <- 1
f1$NewSum <- NA
f1$NewSum <- f1$yearMonth_Max_sum * f1$ChangedX * f1$qunat * f1$NewMedian
write_csv(f1, PathCSV )
f2 <- f1[!duplicated(f1$yearMonth_Max_sum), ]
#plolty plot
Sys.setenv('MAPBOX_TOKEN' = 'pk.eyJ1IjoiY3dvb2RzMjIiLCJhIjoiY2prMnlycmduMDJvNjNxdDEzczNjdGt3YSJ9.RNuCSlHyKZpkTQ8mJmg4aw')
p <- f2[which(f2$yearMonth_Max_sum < 9000),] %>%
plot_mapbox(
lon = ~Lon,
lat = ~Lat,
size = ~yearMonth_Max_sum,
color = ~(NewSum),
frame = ~MY,
type = 'scattermapbox',
mode = 'markers',
colors = c("green","blue")
) %>%
add_markers(text = ~paste("Sum", yearMonth_Max_sum, "/<br>",
"Standard Dev", StdDev, "/<br>",
"Mean", Average, "/<br>",
"Median", Median_Cell, "/<br>",
"Changed", ChangedX, "/<br>",
"Latitude", Lat , "/<br>",
"Longitude", Lon)) %>%
layout(title = C_name,
font = list(color = "black"),
mapbox = list(style = "satellite", zoom = 9,
center = list(lat = Lat,
lon = Lon)))
p
htmlwidgets::saveWidget(p, PathWidg)
}
the last thing in your function is what is returned. you are returning setprogress(1) to renderdatatable()
output$contents <- DT::renderDataTable({
withProgress(message = 'loading...', value = 0.1, {
datatable(data_set(),
options = list(
"pageLength" = 40))
extensions = 'Responsive'
setProgress(1)
})
Try this instead
output$contents <- DT::renderDataTable({
withProgress(message = 'loading...', value = 0.1, {
datatab <- datatable(data_set(),
options = list(
"pageLength" = 40))
extensions = 'Responsive'
setProgress(1)
datatab
})