rCharts with shiny, Cannot see the rChart in Shiny - mysql

I want to create rChart for my data extracted from a mysql database. As shown in ui.R and server.R created ggplot is visible but not the rChart? Can anyone explain what has gone wrong here?
ui.R
library(shiny)
library("shinyBS", lib.loc="/home/thisa/R/x86_64-pc-linux-gnu-library/3.0")
require("rCharts")
options(RCHART_LIB = 'polycharts')
# Define UI for application that plots random distributions
shinyUI(fluidPage(
# Show a plot of the generated distribution
mainPanel(
fluidRow(
column(width=4,
plotOutput("sales")
),
column(width=8,
showOutput("salesR","polycharts")
)
)
)
))
server.R
library(shiny)
library("DBI", lib.loc="/home/thisa/R/x86_64-pc-linux-gnu-library/3.0")
library("RMySQL", lib.loc="/home/thisa/R/x86_64-pc-linux-gnu-library/3.0")
library("ggplot2", lib.loc="/home/thisa/R/x86_64-pc-linux-gnu-library/3.0")
library("shinyBS", lib.loc="/home/thisa/R/x86_64-pc-linux-gnu-library/3.0")
require("rCharts")
con <- dbConnect(MySQL(),
user="root",password="891208",host="localhost",dbname="openPos")
# Define server logic required to generate and plot a random distribution
shinyServer(function(session,input, output) {
sales_total <- reactive({ "SELECT ospos_sales.sale_time,
CAST(sale_time AS date) AS sale_date, ospos_sales.employee_id,
ospos_sales.sale_id, ospos_sales_items.line,
ospos_sales_items.quantity_purchased,
ospos_sales_items.item_cost_price,
ospos_sales_items.item_unit_price,
ospos_sales_items.discount_percent,
ospos_suppliers.person_id,
ospos_suppliers.company_name,
ospos_items.name, ospos_items.category,
ospos_items.supplier_id,
ospos_items.item_number,
ospos_items.quantity,
ospos_items.reorder_level,
ospos_items.location,
sum(quantity_purchased * item_unit_price-item_unit_price*(discount_percent/100))
AS revenue, sum(quantity_purchased * item_cost_price) AS cost
FROM ospos_sales, ospos_sales_items,
ospos_suppliers, ospos_items
WHERE ospos_sales.sale_id = ospos_sales_items.sale_id
AND ospos_sales_items.item_id = ospos_items.item_id
AND ospos_items.supplier_id = ospos_suppliers.person_id
GROUP BY sale_time"})
salesTotal <- reactive({dbGetQuery(con,sales_total())})
output$sales <- renderPlot
({
p<-ggplot(salesTotal(),
aes_string(x="sale_time",y="revenue"))+geom_point()
print(p)})
output$salesR <- renderChart({
m1 <- rPlot(revenue ~ sale_time, data = salesTotal(),type='point')
return(m1)
})
})

Related

Plotly does not work in shiny with HTML function

I'm dealing with a quite complicated shiny app in which I would like to create an UI output inside server function. UI is not that easy and depends on many items created on a server side so I'm creating it concatenating HTML parts of UI. Everything works until I meet plotly chart.
I've created a simpler version of my app to make it easier to understand my problem.
Normally I'd do sth like that:
library("shiny")
library("plotly")
library("dplyr")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
plotlyOutput("distPlot1"),
plotOutput("distPlot2")
)
)
)
server <- function(input, output) {
output$distPlot1 <- renderPlotly({
x <- faithful[, 2]
plot_ly(x = x, type = "histogram")
})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
hist(x)
})
}
shinyApp(ui = ui, server = server)
to obtain this:
But when I start to create ui on server side like here (edited part with more divs inside ui):
library("shiny")
library("plotly")
library("dplyr")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
htmlOutput("ui1"),
uiOutput("ui2")
)
)
)
server <- function(input, output) {
output$distPlot1 <- renderPlotly({
x <- faithful[, 2]
plot_ly(x = x, type = "histogram")
})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
hist(x)
})
output$ui1 <- renderUI({
show <- h1("lfkhg")
show <- paste0(show, plotlyOutput("distPlot1") %>% as.character())
HTML(show)
})
output$ui2 <- renderUI({
show <- h1("lfkhg")
show <- paste0(show, plotOutput("distPlot2") %>% as.character())
HTML(show)
})
}
# Run the application
shinyApp(ui = ui, server = server)
Plotly plot does not appear...
Do you know why and how to deal with this problem?
I dont know why you need %>% HTML() in there as it works for me without it. Also if you want to add more things into the renderUI then simply use tagList and combine them together, here I will add h1 as per your comment
library("shiny")
library("plotly")
library("dplyr")
ui <- fluidPage(
sidebarLayout(sidebarPanel(),
mainPanel(
uiOutput("ui1"),
uiOutput("ui2")
)
)
)
server <- function(input, output) {
output$distPlot1 <- renderPlotly({
x <- faithful[, 2]
plot_ly(x = x, type = "histogram")
})
output$distPlot2 <- renderPlot({
x <- faithful[, 2]
hist(x)
})
output$ui1 <- renderUI({
tagList(h1("lfkhg"),plotlyOutput("distPlot1"))
})
output$ui2 <- renderUI({
plotOutput("distPlot2")
})
}
# Run the application
shinyApp(ui = ui, server = server)

Shiny checkboxGroupInput with Choices Generated From ggplot

I'm trying to create a checkbox for which the choices are plots created through ggplot. In the result, the UI looks like the HTML code itself instead of evaluating the HTML code to show the chart. Any ideas how I can get the checkboxGroupInput to show ggplots?
Sample code below -
runApp(shinyApp(
ui = fluidPage(
headerPanel("Plot check box"),
mainPanel(
uiOutput("plotscheckboxes")
)
),
server = function(input, output, session) {
output$plot1 = renderPlot({
ggplot(mtcars)+geom_point(aes(x=mpg,y=mpg))
})
output$plot2 = renderPlot({
ggplot(mtcars)+geom_point(aes(x=mpg,y=mpg))
})
output$plotscheckboxes = renderUI({
plotlist = list(
plotOutput('plot1'),
plotOutput('plot2')
)
plotlist2 = do.call(tagList, plotlist)
# this just produces a list with 1,2, some sort of underlying value for the checkboxGroup
finaloptionlist = lapply(
seq(length(plotlist2)),
function(x) x
)
# the names of the list are what get used in the options so setting the names accordingly as the HTML code of the ggplot rendering
names(finaloptionlist) = sapply(plotlist2, function(x) paste(x, collapse = "\n"))
checkboxGroupInput("checkGroup", label = h3("Checkbox group"),
choices = finaloptionlist,
selected = 1)
})
}
))

R Shiny: Table object not found in reactive RMySQL query in shiny app

[EDIT]: solution by agstudy worked for me.
I have a shiny app that allows users to toggle between three tables in a MySQL database. Users can select a table which is used by renderTable to generate the object.
I have put if statements in renderTable to respond to the users' selected table.
When I run the app, any table fails to print and cannot be viewed.
server.R
library(shiny)
library(RMySQL)
con <- dbConnect(RMySQL::MySQL(),user="x",password="x",host="dbhost",dbname="db")
shinyServer(function(input, output) {
data <- reactive({
selectInput("input$data", "Choose your Input:", choices = c('data1'='1','data2'='2', 'data3'='3'))
})
output$table <- renderTable({
if(input$data == data1){
query1 <- reactive({ "SELECT *
FROM data1
ORDER BY var1, var2"})
reactive({dbGetQuery(con,query1())})
head(data())
} else if(input$data == data2){
query1 <- reactive({ "SELECT *
FROM data2
ORDER BY var1, var2"})
reactive({dbGetQuery(con,query1())})
head(data())
} else if(input$data == data3){
query1 <- reactive({ "SELECT *
FROM data3
ORDER BY var1, var2"})
reactive({dbGetQuery(con,query1())})
head(data())
} else print("Select a dataset")
})
})
ui.R
library(shiny)
library('RMySQL')
shinyUI(navbarPage("Test",
tabPanel("Test",
sidebarLayout(
sidebarPanel(
selectInput("data", label = "Data set",
choices = c("", "data1", "data2", "data3"))
),
mainPanel(
tableOutput("table")
)
))
))
Your problem here is not in any case related to MySQLserver but there is a no UI logic. Programming in Shiny is not easy if you don't isolate your code parts:
inputs: defined in your ui interface
reactive functions : should change each time you change your input
outputs: be refreshed once the input data is changed by the reactive function.
You miss-understand the reactive.The basic idea is that your don't need to refresh your UI manually, it should be done automatically once the input parameter is changed.
Here I am rewriting completely your code using the Shiny logic:
library(RMySQL)
library(shiny)
## this a public function that will be used
## in the server side to connect to the data base
## and retrieve data
get_data <-
function(query){
on.exit(dbDisconnect(conn)) ## important to close connection
conn <- dbConnect("MySQL",user="xuser",
password="xpws",
host="xhost",
dbname="xdbname")
dbGetQuery(con,query)
}
server <- shinyServer(
function(input, output) {
## the reactive engine that will refresh query
## each time input changed
query <- reactive( sprintf("SELECT *
FROM %s
ORDER BY var1, var2",input$data)
)
## simply displaying reactive inputs
output$table <- renderTable(
if(input$data!="") get_data(query())
)
})
## define ui elements by step
## for easy indenting
ui_panel <-
tabPanel("Test",
sidebarLayout(
sidebarPanel(
selectInput("data", label = "Data set",
choices = c("","data1", "data2", "data3"))
),
mainPanel(
tableOutput("table")
)
)
)
ui <- shinyUI(navbarPage("Test",ui_panel))
runApp(list(ui=ui,server=server))

CSV quick plot error

I would like to use the CSV quick plot application to analyze data however even with all the packages installed the app continues to show an error. The error message is:
Error in file(file, "rt") : cannot open the connection
Warning in run(timeoutMs) :
cannot open file
The code is below:
UI
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("CSV Quick Plot"),
sidebarPanel(
fileInput('infile', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
),
selectInput("plotType", label = "Select Plot Type",
c("Histogram" = "hist",
"Correlation" = "corr")),
dateInput("date", "Date:"),
submitButton("Submit")
),
mainPanel(
h3('Output Information'),
h4('File entered'),
verbatimTextOutput("ofile"),
h4('You selected plot type'),
verbatimTextOutput("oplotType"),
h4('You entered'),
verbatimTextOutput("odate"),
plotOutput('newHist')
)
))
server
library(UsingR)
library(shiny)
library(Hmisc)
library(corrplot)
wd <- getwd()
setwd(wd)
shinyServer(
function(input, output) {
output$ofile <- renderPrint({input$infile})
output$oplotType <- renderPrint({input$plotType})
output$odate <- renderPrint({input$date})
plotdata <- reactive({
filestr <- input$infile
read.csv(filestr$name)
if(is.null(input$file1))
return(NULL)
})
output$newHist <- renderPlot({
hist(plotdata())
})
# Conditional plot selection is test in progress
# corrdf <- cor(plotdata)
# output$newHist <- renderPlot({
# corrplot(corrdf, method = "circle")
# })
}
)
Please help me in getting this application to run. Thank you!
There are three problems with your code.
you're checking for if(is.null(input$file1)) but I believe you want to use input$infile
the above check should be done BEFORE read.csv because if there is no file chosen, you don't want to read a file
when reading the file you want to use filestr$datapath instead of filestr$name. The name only gives you the name of the file on the user's local machine, while the datapath gives the actual full path to the file that's been uplodaed
Here is a simplification of your app that only deals with selecting a file and reading it into csv, demonstrating all those points
runApp(shinyApp(
ui = fluidPage(
fileInput('infile', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv'
)
)
),
server = function(input, output, session) {
plotdata <- reactive({
if (is.null(input$infile)) {
return()
}
filestr <- input$infile
read.csv(filestr$datapath)
})
observe({
cat(str(plotdata()))
})
}
))

selectInput in R shiny

I want to select from a list read in from a Mysql query. I am getting an error in the code. I must be doing something just completely wrong, but not sure what.
I would like to select from a list of skus read in from a sql query. I get an error in the ui portion.
I am not even sure if this is possible, but to list out all skus would be extremely timely.
I am getting the following errors:
Error in tag("div", list(...)) :
argument "sidebarPanel" is missing, with no default
shinyApp(ui = ui, server = server)
Error in force(ui) : object 'ui' not found
library('RMySQL')
library('plyr')
library('shiny')
library('scales')
library(shinyapps)
library(ggplot2)
con <- dbConnect(MySQL(), user="user", password="password",dbname="DB", host="host");
rank<-dbGetQuery(con,"select sku from DB")
#build a shiny app to select which sku to pick
server <- function(input, output) {
output$distPlot <- renderPlot({
hist(rnorm(input$obs), col = 'darkgray', border = 'white')
})
}
ui <- pageWithSidebar(
## Application title
sidebarPanel(
sliderInput("obs", "Number of observations:", min = 10, max = 500, value = 100),
selectInput(
'e0', '0. An ordinary select input', choices = unique(rank$sku),
selectize = FALSE
),
mainPanel(plotOutput("distPlot"))
)
)
shinyApp(ui = ui, server = server)
You have both a missing bracket near your selectize = FALSE and (as #DavidRobinson has suggested) you need a headerPanel.
CODE FIX
library(shiny)
library(ggplot2)
# con <- dbConnect(MySQL(), user="user", password="password",dbname="DB", host="host");
# rank<-dbGetQuery(con,"select sku from DB")
# for test hard coding the rank as I dont have your data
# test rank
rank$sku <- c(1,2,3)
#build a shiny app to select which sku to pick
server <- function(input, output) {
output$distPlot <- renderPlot({
hist(rnorm(input$obs), col = 'darkgray', border = 'white')
})
}
ui <- pageWithSidebar(
## Application title
# missing headerPanel
headerPanel(title = "Hello"),
# missing bracket after selectize
sidebarPanel(
sliderInput("obs", "Number of observations:", min = 10, max = 500, value = 100),
selectInput(
'e0', '0. An ordinary select input', choices = unique(rank$sku),
selectize = FALSE)
),
mainPanel(plotOutput("distPlot"))
)
shinyApp(ui = ui, server = server)
RESULT
ANOTHER SHINY PAGE UI OPTION
You can can also use a tabbed page structure, replacing ui above with this code (note it does not require headerPanel like above):
# navbar tabbed page example - without headerPanel
ui2 <- navbarPage(title = "Hello Another Style",
tabPanel("Chart Panel",
sidebarLayout(
sidebarPanel(
sliderInput("obs", "Number of observations:",
min = 10, max = 500, value = 100),
selectInput(
'e0', '0. An ordinary select input',
choices = unique(rank$sku),
selectize = FALSE)
),
mainPanel(
plotOutput("distPlot")
)
)
),
tabPanel("Instructions",
mainPanel(
p("Notes here for example...")
)
)
)
SECOND RESULT
And then on second panel...
DEBUGGING ADVICE
These Shiny pages can have lots of brackets, so pace over your code selecting brackets in turn carefully in your editor like RStudio to make sure your brackets match okay.
All the best!