rCharts d3pie not showing up in shiny app - r

I am working with a d3pie rChart. It works when I view it in the rStudio viewer. When I try to enter it into a shiny app, I get an error:
Error in addResourcePath(LIB$name, LIB$url) : object 'LIB' not found
It wants me to tell it what library I am working with in showOutput('chart1','LIB') (e.g., Nvd3, Highcharts), but I'm not sure which one to use.
Similarly, when I save the d3pie chart as an html file, it won't open in my browser. Is there a way around this?
Data:
x <- data.frame(table = as.factor(c("A","B","C","D","E","F")),
value = c(518,39,337,304,56,7))
Code for d3pie:
require(magrittr)
require(dplyr)
require(rCharts)
rPie <- rCharts$new()
rPie$setLib("http://timelyportfolio.github.io/rChartsExtra/d3pie")
rPie$addParams(
chartspec = list(
header = list(
title = list(
text = "Breakdown of 2014 Revenue Sources"
)
)
,data = list(
content = x
)
)
)
rPie
server.R:
require(rCharts)
require(reshape)
require(magrittr)
require(dplyr)
x <- data.frame(table = as.factor(c("A","B","C","D","E","F")),
value = c(518,39,337,304,56,7))
shinyServer(function(input, output) {
output$chart1 <- renderChart2({
rPie <- rCharts$new()
rPie$setLib("http://timelyportfolio.github.io/rChartsExtra/d3pie")
cat(add_lib_assets(rPie$lib,cdn=T))
rPie$addParams(
chartspec = list(
header = list(
title = list(
text = "This is the title"
)
)
, data = list(
content = x
)
)
)
rPie$set(dom = "chart1")
return(rPie)
})
})
ui.R:
require(rCharts)
shinyUI(fluidPage(
titlePanel("Shiny App"),
mainPanel(
showOutput('chart1')
)
)
)

To make it work in shiny, you need to add d3pie as the lib in your showOutput:
showOutput('chart1','d3pie')
You also to download the extra libraries and copy/paste the d3pie folder in the same folder as where your server.R and ui.R are.

Related

Update plotly data (chloropleth) in R shiny without re-rendering entire map

I am trying to use shiny controls to modify the data underlying a plotly chloropleth map.
Whenever I change the data the entire plot re-renders, which is quite slow. I'm guessing the bottleneck is redrawing the geojson polygons. Because the geojson never changes, I'm wondering if there is a way to keep the rendered widget intact but modify the z values only.
It looks like using plotlyProxy and plotlyProxyInvoke might be the right direction, but I can only see examples of an entire trace (which includes the geojson data) being replaced.
Sorry if I'm missing something or have been unclear - I have not used plotly very much, and even less so the js side of things.
See below for example code:
library(shiny)
library(dplyr)
library(plotly)
library(readr)
library(rjson)
zip_geojson <- fromJSON(file="https://raw.githubusercontent.com/hms1/testData/main/zip3_2.json")
plot_data <- read_csv(file="https://raw.githubusercontent.com/hms1/testData/main/plot_data.csv")
mapboxToken <- "pk.eyJ1IjoiaG1vcmdhbnN0ZXdhcnQiLCJhIjoiY2tmaTg5NDljMDBwbDMwcDd2OHV6cnd5dCJ9.8eLR4FtlO079Gq0NeSNoeg" #burner token
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("multip",
"n:",
min = 1,
max = 10,
value = 1)
),
mainPanel(
plotlyOutput("cPlot")
)
)
)
server <- function(input, output) {
output$cPlot <- renderPlotly({
plot_data_i <- plot_data%>%
mutate(log_count = case_when(log_count <= input$multip ~ log_count * input$multip,
TRUE ~ log_count))
plot_ly() %>%
add_trace(
type = "choroplethmapbox",
geojson = zip_geojson,
locations = plot_data_i$zip,
z = plot_data_i$log_count
) %>%
layout(
mapbox = list(
style = "light",
zoom = 3,
center = list(lon = -95.7129, lat = 37.0902)
)
) %>%
config(mapboxAccessToken = mapboxToken)
})
}
shinyApp(ui = ui, server = server)
For anyone else who comes across this post later, I found a solution.
It turns out that you can change data using the restyle method in plotlyProxyInvoke, as shown below.
library(shiny)
library(dplyr)
library(plotly)
library(readr)
library(rjson)
zip_geojson <- fromJSON(file="https://raw.githubusercontent.com/hms1/testData/main/zip3_2.json")
plot_data <- read_csv(file="https://raw.githubusercontent.com/hms1/testData/main/plot_data.csv")
mapboxToken <- "pk.eyJ1IjoiaG1vcmdhbnN0ZXdhcnQiLCJhIjoiY2tmaTg5NDljMDBwbDMwcDd2OHV6cnd5dCJ9.8eLR4FtlO079Gq0NeSNoeg"
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
sliderInput("multip",
"n:",
min = 1,
max = 10,
value = 1),
actionButton("Remove", "Remove Trace")
),
mainPanel(
plotlyOutput("cPlot")
)
)
)
server <- function(input, output, session) {
output$cPlot <- renderPlotly({
plot_ly(type = "choroplethmapbox", geojson = zip_geojson) %>%
layout(
mapbox = list(
style = "light",
zoom = 3,
center = list(lon = -95.7129, lat = 37.0902)
)
) %>%
config(mapboxAccessToken = mapboxToken)
})
plotproxy <- plotlyProxy("cPlot", session, deferUntilFlush = FALSE)
observeEvent(input$multip, {
plot_data_i <- plot_data %>%
mutate(log_count = case_when(log_count <= input$multip ~ log_count * input$multip,
TRUE ~ log_count))
plotproxy %>%
plotlyProxyInvoke("restyle", list(z = list(plot_data_i$log_count),
locations = list(plot_data_i$zip)))
})
}
shinyApp(ui = ui, server = server)

Rshiny--creation of bar plot using CSV file

I want the bar plot to be embedded into application.output of vector d is giving me result I want that to be embedded into shinyapp and later I want to make it interactive too.
library(ggplot2)
driver1 <- read.csv("E:/RMARKDOWN/shiny/driver.csv",header = T)
New_DataSet1<-
data.frame(driver1$ï..Year_AG,driver1$Severity_Desc,driver1$Injury.Type)
New_DataSet1
latest <- New_DataSet1[1:100,]
latest
d <- aggregate(latest$driver1.Injury.Type, by=list(chkID =
latest$driver1.Severity_Desc), FUN=sum)
ui <- dashboardPage(
dashboardHeader(title = "Row layout"),
dashboardSidebar(),
dashboardBody()
)
server <- function(input, output) {
#output$plot <- renderPlot({ barplot(d$x, xlab = d$chkID) })
renderPlot(d$x)
#barplot(d$x, xlab = d$chkID)
# barplot(d$x, names.arg = d$chkID)
}
shinyApp(ui,server)
You can read file first and render it using bar chart as below:
library(plotly)
library(shiny)
ui <- fluidPage(
mainPanel(
plotlyOutput("chart")
)
)
server <- function(input, output, session) {
output$chart <- renderPlotly({
# write code here to read data from csv file
df=read.csv("")
# Set x and y axis and display data in bar chart using plotly
p <- plot_ly( x = iris$Species,
y = iris$Sepal.Length,
name = "Iris data",
type = "bar")
})
}
shinyApp(ui, server)
Screenshot from working demo:

Produce a graph from an editable table in Shiny

I have a shiny application with the following ui:
library(rhandsontable)
library(shiny)
library(ggplot2)
ui = fluidPage(
# App title ----
titlePanel("Tabsets"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(type = "tabs",
tabPanel("Summary", rHandsontableOutput('contents'),
actionButton("saveBtn", "Save changes")
),
tabPanel("Tab",
rHandsontableOutput('contentFinal')),
tabPanel("Dashboard",
plotOutput('dashboard1'))
)
)
)
)
And the following server
library(dplyr)
library(rhandsontable)
options(shiny.maxRequestSize = 9*1024^2)
server = function(input, output) {
values <- reactiveValues()
Post <- c("", "")
list2 <- c(12,13)
df <- data.frame(Post, list2)
output$contents <- renderRHandsontable({
rhandsontable(df, width = 550, height = 300) %>%
hot_col(col = "Post", type = "dropdown")
})
saveData <- eventReactive({input$saveBtn},{
finalDF <- hot_to_r(input$contents)
finalDF$Post <- ifelse(finalDF$Post =="",NA,finalDF$Post)
newDF <- finalDF[complete.cases(finalDF),]
return(newDF)
})
output$contentFinal <- renderRHandsontable(
rhandsontable(saveData())
)
output$dashboard1 <- renderPlot(
ggplot(input$contentFinal, aes(x = Post, y = list2 )) +
geom_bar(stat = "identity")
)
observeEvent(input$saveBtn, saveData())
}
shinyApp(ui = ui, server = server)
The flow is like this:
In the first tab, I bring up data with an empty post column
In this tab, I can add a name for the post and save it.
As soon as I save he rows with values for post become visible in the next tab.
Then the next thing I want to do is to have a visual in the dashboard tab that shows the data. Therefore I create:
output$dashboard1 <- renderPlot(
ggplot(input$contentFinal, aes(x = Post, y = List2 )) +
geom_bar(stat = "identity")
)
This however gives me the following ggplot2 errror:
ggplot2 doesn't know how to deal with data of class list
Any thoughts on what goes wrong here?
The problem is because input$contentFinal is handsontable data. We need to convert it to R object using hot_to_r function.
The ggplot should be plotted using the following:
ggplot(hot_to_r(input$contentFinal), aes(x = Post, y = list2 )) +
geom_bar(stat = "identity")
Hope it helps!

An error occurred rendering the PivotTable results

I try to create shiny app with
rpivotTable and nvd3 rcharts
all works , but when i try to to show any chart from pivot
i get error
An error occurred rendering the PivotTable results.
But if i use only rpivotTable charts works in pivot and i think that there is problem when using rpivotTable and nvd3 rcharts in one shiny app.
Example
UI
library(shiny)
library(rCharts)
library(rpivotTable)
shinyUI(fluidPage(
showOutput('plot1',lib = "nvd3"),
rpivotTableOutput('pivot1', width = "100%", height = "500px"))
)
Server
library(shiny)
library(rCharts)
library(rpivotTable)
df=data.frame(A=c(1:10),B=c(-10:-1),C=c("x",rep(c("x","y","z"),3)))
shinyServer(function(input, output, session) {
output$pivot1 <- renderRpivotTable({
rpivotTable(data =df ,
width="100%", height="500px")
})
output$plot1=renderChart2({
myform <- as.formula(paste('A','~','B'))
n2 <- nPlot(myform, group ="C", data = df, type = 'multiBarChart')
n2$chart(margin = list(left = 100))
n2$chart(reduceXTicks = F)
n2$set(width = 800, height = 500)
print(n2)
})
})
Give me
If i use only rpivotTable charts in pivot works
When i look at inspect i see
TypeError: a.axisTimeFormat.multi is not a function
at e.i.initParams (c3.min.js:1)
at e.i.init (c3.min.js:1)
at new d (c3.min.js:1)
at Object.k.generate (c3.min.js:1)
at Object.renderer (c3_renderers.coffee:129)
at t.fn.pivot (pivot.coffee:546)
at pivot.coffee:835
Is there way to fix it?
Package versions :
rpivotTable_0.1.5.7
rCharts_0.4.2
shiny_0.12.2.9005
Thanks!
As pointed out in the comments, this is due to the double loading of the n3 libraries. To avoid this issue (this is more of a hack than a fix), you could plot the rcharts frame in an iframe to avoid js and css issues.
To do this, you can use uiOutput/renderUI for the shiny part, and show to output the rCharts.
Here's an example:
library(shiny)
library(rCharts)
library(rpivotTable)
df=data.frame(A=c(1:10),B=c(-10:-1),C=c("x",rep(c("x","y","z"),3)))
ui <-shinyUI(fluidPage(
uiOutput('plot1'),
rpivotTableOutput('pivot1')
))
server <- shinyServer(function(input, output, session) {
output$pivot1 <- renderRpivotTable({
rpivotTable(data =df)
})
output$plot1=renderUI({
myform <- as.formula(paste('A','~','B'))
n2 <- nPlot(myform, group ="C", data = df, type = 'multiBarChart')
n2$chart(margin = list(left = 100))
n2$chart(reduceXTicks = F)
HTML(paste(capture.output(n2$show('iframesrc', cdn = TRUE)), collapse = '\n'))
})
})
shinyApp(ui,server)

Chart not generated in R shiny when run locally using googleVis

These are the codes for my UI and server. The issue that I am facing is that when the app is run locally the charts are not being generated.
ui.R
library(googleVis)
library(shiny)
shinyUI(fluidPage(
titlePanel(" Tool"),
sidebarLayout(
sidebarPanel(
radioButtons(inputId="choice", label="What would you like to see?",
choices=c("Overall ","Individual"))
),
mainPanel(
htmlOutput("View")
)
)
))
server.R
library(googleVis)
require(googleVis)
shinyServer(function(input, output) {
n = 100
dates = seq(Sys.Date(), by = 'day', length = n)
x = 10 * rnorm(n)
y = 3 * x + 1 + rnorm(n)
label = rep(LETTERS[1:4], each=25)
label[1] = "D"
my.data = data.frame(Date = dates, x, y, label)
output$view <- renderGvis({
gvisMotionChart(my.data, idvar ='label', xvar = 'x', yvar = 'y', timevar= 'Date')
})
}
)
Looks like you have a couple things going wrong here. First, you should have a library open to shiny in both server.R and ui.R; it looks like you reproduced googleVis twice in server.R. In addition I found you capitalized the 'v' in htmlOutput('view'), but this should match the output$view path in server.R which is not capitalized.
On top of this the radio buttons seem superfluous or I do not understand the intent. Typically radio buttons are used so that their input can be fed to a reactive environment in server.R to change a dataset or some other parameter (see shiny tutorial or this example: https://github.com/rstudio/shiny-examples/blob/master/006-tabsets/server.R).
Code below will produce the plot and I have left the radio buttons even though they serve no purpose.
ui.R
library(googleVis)
library(shiny)
shinyUI(fluidPage(
titlePanel(" Tool"),
sidebarLayout(
sidebarPanel(
radioButtons(inputId="choice", label="What would you like to see?",
choices= c("Overall ","Individual"))
),
mainPanel(
htmlOutput("view")
)
)
))
server.R
library(googleVis)
library(shiny)
shinyServer(function(input, output) {
n = 100
dates = seq(Sys.Date(), by = 'day', length = n)
x = 10 * rnorm(n)
y = 3 * x + 1 + rnorm(n)
label = rep(LETTERS[1:4], each=25)
label[1] = "D"
my.data = data.frame(Date = dates, x, y, label)
output$view <- renderGvis({
gvisMotionChart(my.data,
idvar ='label',
xvar = 'x',
yvar = 'y',
timevar= 'Date')
})
})
Be sure to also open it to a browser after the app is launched. Hope that helps.

Resources