rCharts and highcharts with shiny plot does not update correctly - r

I've created a custom plotting function for a scatterplot with error bars on multiple series using rCharts. I successfully embedded said plot in a shiny application. The first time it shows everything works fine:
However, if I try to update the plot (e.g. by changing some input) the plot does not change and I get the following JS error message on the browser's console:
TypeError: 'undefined' is not a function (evaluating 'this[b].destroy()')
The strange thing is that if I check the plot object (p) it seems fine, e.g. I can plot it in Rstudio and also get a viable html page from it. I guess the problem is somehow that the old plot cannot be removed properly.
I use rCharts v. 0.4.5 and shiny 0.10.2.1 and I have uploaded an example shiny app to github:
https://github.com/mlist/highcharts_scatterplot_example
As extra dependency you will need to install the packages rjson and foreach. You can then run the app with
runGitHub(repo="mlist/highcharts_scatterplot_example")
```

Use renderChart2 rather then renderChart. Replace output$testPlot with :
output$testPlot <- renderChart2({
p <- highcharts.scatterplot.plate(data.frame(seq(1:nrow(iris)),iris[,2], input$error, iris[,5]))
return(p)
})
You can try the change at:
shiny::runGitHub(repo="johndharrison/highcharts_scatterplot_example")

Related

WebviewPanel: FAILED posting webview/editors/didChangeVisible to the webview

I have graph output in the R/Radian console and in Jupyter, Jupyterlab, and VS Code notebooks. I also get the Rplots.pdf sent to the working directory as expected. However, I don't get embedded "pop-up" graph output when running R scripts in the VS Code editor e.g. filename.R. I always get this error message from CodeStream.
WebviewPanel: FAILED posting webview/editors/didChangeVisible to the webview; Webview is invisible and can't receive messages.
I've read a few SO questions on the Webviews, but they seem to be related to web/JSON loading issues and not R plots.
Seems I am missing a setting or package that pushes the Webview out.
Example code block if needed.
data("mtcars")
cars <- mtcars
print(nrow(cars))
print(head(cars, 10))
x <- c(0:10)
plot(x, sin(x))

Export plot from plotly into PDF

I use package plotly in order to make some plots. And the end my intention is to put this plot with high resolution in pdf. I don't know way but ggplot2 give me permission to do this, but with plotly I can't use option from R-Studio and convert directly into PDF. You can see that on pic below:
In order to fix this problem I try to do this with this lines of code:
pdf(file=paste("FINAL_plot.pdf",sep=""),width=10, height=5)
op <- par(mgp=c(1,0,0),mar=c(2, 2, 1, 1),# Room for the title and legend: 1_bottom,2_left,3_up,4_right
mfrow=c(1,2))
plot(FINAL_plot)
dev.off()
But unfortunately this lines of code didn't work and PDF is empty. So can anybody help me how to resolve this problem ?
Plotly plots can only be exported using the additional orca command line utility (https://github.com/plotly/orca)
You would first need to install the orca library on your OS (see https://github.com/plotly/orca#installation for details). After that you can export your plot using
library(plotly)
orca(FINAL_plot, "FINAL_plot.pdf")
Orca is now deprecated. You now must use Kaleido to install. In similarity to Orca, you must first have the Kaleido library installed on your OS.
To install:
install.packages('reticulate')
reticulate::install_miniconda()
reticulate::conda_install('r-reticulate', 'python-kaleido')
reticulate::conda_install('r-reticulate', 'plotly', channel = 'plotly')
reticulate::use_miniconda('r-reticulate')
To export:
library(plotly)
kaleido(FINAL_plot, "FINAL_plot.pdf")

Non-numeric argument to binary operator in Shiny using ggplot

I am writing my first Shiny app trying to port a code for plotting maps of Spain into a Shiny app that anyone with no knowledge of R can use.
Lately I have come up with a problem when trying to alter a ggplot returned by a function.
I will post a simplified version of my code.
I first have a function in helper.R that takes various inputs from the ui and returns a gg and a dataframe:
graphing=function(datax,setter,selCCAA,varsel){
map=readShapeSpatial('prov_map.shp')
map#data$CodProv=as.integer(map#data$CodProv)
map#data=merge(map#data,datax,by.x='CodProv',by.y='CodProv',sort=F)
map#data$id=rownames(map#data)
map.points=fortify(map,region='id')
map.df=join(map.points,map#data,by='id')
map.df$Cd_CCAAint=as.integer(map.df$Cd_CCAA)
if(varsel=="-"){return (NULL)}
else {
if (setter==0){
mapa=ggplot(map.df)+
aes_string("long","lat",group="group",fill=varsel)+
geom_polygon()+
geom_path(color='white')+
coord_equal()
return(list(mapa,map.df))
}
else {
map.dfx<-subset(map.df,map.df$Cd_CCAAint==selCCAA)
mapa=ggplot(map.dfx)+
aes_string("long","lat",group="group",fill=varsel)+
geom_polygon()+
geom_path(color='white')+
coord_equal()
return(list(mapa,map.dfx))
}
}
}
Then, in server.R, I take the gg that is returned by the function and add more lines to it so the user can personalize the graphs' colors, midpoint etc.
output$plot=renderPlot({
mapa=graphing(dataini,input$setter,input$selCCAA,input$varsel)
grafico=mapa[[1]]+
scale_fill_gradient2(low='#89D1F3',high='#006EC1')+
theme(legend.position='bottom',axis.title.x=element_blank(),
axis.title.y=element_blank(),axis.ticks=element_blank(),axis.text=element_blank(),
panel.grid.minor=element_blank(),panel.grid.major=element_blank())
grafico
})
When I run the app including the line scale_fill_gradient2 or any type of geom I get the following error:
Warning: Error in +: non-numeric argument to binary operator
The error does not appear when I just include the theme.
Up to now, the two lines had been included in the graphing function and the App had been running perfectly*, but I need them to be in server.R so the graph can be personalized as stated before.
*:that version of the App can be tested using runGitHub("Mapas_BBVA_provincias","IArchondo"). Any help with the display of spanish characters such as ñ in the ui, would be extremely welcome as well.
That's the error you get from
NULL + scale_fill_gradient2(low='#89D1F3',high='#006EC1')
Since your graphing function begins with if(varsel=="-"){return (NULL)}, my guess is this error is created when varsel is "-". Try returning a blank ggplot object instead when nothing is selected.
if(varsel=="-"){return (ggplot())}

R Leaflet: lines missing when plotting polylines

I have a pretty simple spatial object composed of a bunch of lines. I can plot it in different ways with no problems: QGIS, mapshaper.org. Even the standard R plot() function:
But when I plot it with leaflet(), some segments mysteriously disappear, leaving disconnected lines behind:
A reproducible example follows. NOTE: I use a GeoJSON source file for simplicity here. I have also tried saving the lines as an ESRI shapefile, with the same effect: The data is plotted OK with QGIS, or plot(), etc but not with leaflet().
library(leaflet)
library(rgdal)
download.file("https://www.dropbox.com/s/nij2oa2rp7ijaaj/commuter_rail.geojson?dl=1",
method = "auto", mode = "wb", destfile = "commuter_rail.json")
commuterLines <- readOGR("commuter_rail.json",
"OGRGeoJSON")
# Straight R Plot - Looks good
plot(commuterLines)
# Plot using leaflet - Some lines are missing!
leaflet() %>% addPolylines(data = commuterLines)
UPDATE:
Here's the reproducible example running as a shiny app, hosted at shinyapps.io, and showing the weird leaflet behavior: https://havb.shinyapps.io/leaflet_example/
UPDATE: the problem seems to be a bug in an older version of the leaflet package available from CRAN. Installing the latest development version from Github resolves the issue.
I don't have enough rep to comment, but I tried your code and it worked for me:
Perhaps it has something to do with your local configuration? Have you tried reinstalling the leaflet package?

Plotting with gWidgetstcltk

I've made a gui with a button, the handler of which executes a plot method of a class I made, it uses ggplot2 and grid/gridExtra in a normal R session to put together the plot. It works fine using the plot() function in console. My button/handler is below:
Plotbutton <- gbutton("Plot!", container=MainWindow,
handler=function(h,...){
plot(analysis, linesplot=svalue(linecheck), lineplot.legend=svalue(linelegcheck), baseannotate=svalue(bpcheck), bpfreq=as.numeric(svalue(bpspin)), mosaic.bars=svalue(mosaiccheck), mosaic.scale=as.numeric(svalue(mosaicspin)), combine.plots=svalue(combinecheck), condense.mosaics=svalue(condensecheck), labfontsize=as.numeric(svalue(fontspin1)), legfontsize=as.numeric(svalue(fontspin2)))
})
I'm not sure of the reason, but loading gWidgets, gWidgetstcltk, and the package required for my plot method, and then clicking the button, nothing is plotted to the R graphics environment, however in RStudio the plot panel is not updated until the GUI is exited. The graphic does appear in a window in the normal Windows RGui though.
Can anyone suggest why this is happening?
The reason why it works from the R-console and not from a function is that the R-console will invoke print() automatically if nothing else is stated. Within a function R does not do this, so if you want to print a graph, you must explicitly state print(graph). Try
print(plot(analysis, linesplot=svalue(linecheck), lineplot.legend=svalue(linelegcheck), baseannotate=svalue(bpcheck), bpfreq=as.numeric(svalue(bpspin)), mosaic.bars=svalue(mosaiccheck), mosaic.scale=as.numeric(svalue(mosaicspin)), combine.plots=svalue(combinecheck), condense.mosaics=svalue(condensecheck), labfontsize=as.numeric(svalue(fontspin1)), legfontsize=as.numeric(svalue(fontspin2)))

Resources