I'm looking for guidance on getting a basic example of leafletR package to show a map in the browser. Working with the most basic example, the map doesn't show up in the browser. I've checked the .html and .json files, which are present and appear to properly formatted. Javascript inspector shows this error:
XMLHttpRequest cannot load file:///var/folders/_0/tdgf_k7x77qdn64_gk9ynljm0000gp/T/Rtmp6O4QZM/Fiji_Earthquakes/quakes.geojson. Received an invalid response. Origin 'null' is therefore not allowed access.
I'm on a Mac: OSX 10.7.5
RStudio Version: 0.98.857
Code
library(leafletR)
data(quakes)
# store data in GeoJSON file (just a subset here)
q.dat <- toGeoJSON(data=quakes[1:99,], dest=tempdir(), name="quakes")
# make style based on quake magnitude
q.style <- styleGrad(prop="mag", breaks=seq(4, 6.5, by=0.5), style.val=rev(heat.colors(5)), leg="Richter Magnitude", fill.alpha=0.7, rad=8)
# create map
q.map <- leaflet(data=q.dat, dest=tempdir(), title="Fiji Earthquakes", base.map="osm", style=q.style, popup="mag")
# view map in browser
browseURL(q.map)
Thank you in advance for any advise.
A quick solution to open the map using a local web server is to take advantage of RStudio's HTML viewer.
rstudio::viewer(qmap)
The trick is to include incl.data=TRUE in the leaflet function. For example,
map<-leaflet(data=leafdat, dest=downloaddir, style=sty,
title="index", base.map="osm",
incl.data=TRUE, popup=popup)
Check out this post that shows how to do this in detail.
Related
I'm trying to harvest data using rvest (also tried using XML and selectr) but I am having difficulties with the following problem:
In my browser's web inspector the html looks like
<span data-widget="turboBinary_tradologic1_rate" class="widgetPlaceholder widgetRate rate-down">1226.45</span>
(Note: rate-downand 1226.45 are updated periodically.) I want to harvest the 1226.45 but when I run my code (below) it says there is no information stored there. Does this have something to do with
the fact that its a widget? Any suggestions on how to proceed would be appreciated.
library(rvest);library(selectr);library(XML)
zoom.turbo.url <- "https://www.zoomtrader.com/trade-now?game=turbo"
zoom.turbo <- read_html(zoom.turbo.url)
# Navigate to node
zoom.turbo <- zoom.turbo %>% html_nodes("span") %>% `[[`(90)
# No value
as.character(zoom.turbo)
html_text(zoom.turbo)
# Using XML and Selectr
doc <- htmlParse(zoom.turbo, asText = TRUE)
xmlValue(querySelector(doc, 'span'))
For websites that are difficult to scrape, for example where the content is dynamic, you can use RSelenium. With this package and a browser docker, you are able to navigate websites with R commands.
I have used this method to scrape a website that had a dynamic login script, that I could not get to work with other methods.
I'm having some issues displaying an interactive map in R-Shiny that incorporates a KML file. I installed leaflet-plugins and was able to create an HTML file that displays properly by itself in the browser but not within Shiny. This attempt followed an example here - the code is available if you view source.
Because this initial version does not require the HTML itself to change, I attempted to follow the samples here to include the raw HTML in my page but I receive a 404 error with these as well as when I attempted to include it as an iframe within R-Shiny (following this discussion). I then set up an external facing server for both the KML file and the HTML file and got the same result.
I was able to get a map working without the KML file with leaflet-shiny but I'm frankly not sure how to add the KML file and don't see this in the documentation.
Finally, I tried rMaps which does have a "addKML" method, but I can't get it working with various locations of files on my server (
map1 = Leaflet$new()
map1$setView(c(45.5236, -122.675), 13)
map1$tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
map1$addKML('http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml')
map1
It works without the $addKML line. It might be worth noting that the tilelayer line on example 1 here also resulted in a blank map.
I actually have some possibly similar issues hosting derived title layers that are still unresolved which is one reason I opted for uses KML layers for this demo version of the application, which is why I tagged networking on here as well. I'm using Digital Ocean.
Thank you for any thoughts or pointers you may have.
I think there may be a small issue in the rMaps library. If you inspect the config.yml file
https://github.com/ramnathv/rCharts/blob/master/inst/libraries/leaflet/config.yml you will see that for
content delevery network (cdn) there is reference to
"http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js". This KML reader is a plugin for leaflet from https://github.com/shramov/leaflet-plugins/blob/master/layer/vector/KML.js. When content is delivered locally:
css: [external/leaflet.css, external/leaflet-rCharts.css, external/legend.css]
jshead:
- external/leaflet.js
- external/leaflet-providers.js
- external/Control.FullScreen.js
there is no reference to this javascript file. We can fix this:
require(yaml)
leafletLib <- file.path(find.package("rMaps"), "libraries", "leaflet")
rMapsConfig <- yaml.load_file(file.path(leafletLib, "config.yml"))
# add a kml library
kmlLib <- readLines("http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js")
write(kmlLib, file.path(leafletLib, "external", "leaflet-kml.js"))
# add the library to config.yml
rMapsConfig$leaflet$jshead <- union(rMapsConfig$leaflet$jshead , "external/leaflet-kml.js")
write(as.yaml(rMapsConfig), file.path(leafletLib, "config.yml"))
Now the config.yml will contain the necessary link to the KML reader and there is a local copy stored now in external/leaflet-kml.js. Our example still wont work however as we will get a Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml. This can be fixed by moving the resource to the same domain or enabling CORS.
We will need to have this file served locally. We can place it as a temporary measure in the leaflet folder in the rMaps package. When a map is created this folder gets copied to a temporary file:
require(rMaps)
map1 = Leaflet$new()
map1$setView(c(45.5236, -122.675), 13)
map1$tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
map1$addKML('leaflet/placemark.kml')
# temp copy http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml
# to rMaps
sampleKml <- readLines('http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml')
write(sampleKml, file.path(leafletLib, 'placemark.kml'))
# finally try the map
map1
# remove the temp file
file.remove(file.path(leafletLib, 'placemark.kml'))
UPDATE:
There is an addAssets method in rCharts which allows you to add .js files. This allows us to simpilfy things and doesnt require us to write a copy of the js file nor edit the config.yml file.
require(rMaps)
map1 = Leaflet$new()
map1$setView(c(45.5236, -122.675), 13)
map1$tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
map1$addAssets(css = NULL, jshead = 'http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js')
map1$addKML('leaflet/placemark.kml')
leafletLib <- file.path(find.package("rMaps"), "libraries", "leaflet")
sampleKml <- readLines('http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml')
write(sampleKml, file.path(leafletLib, 'placemark.kml'))
# finally try the map
map1
# remove the temp file
file.remove(file.path(leafletLib, 'placemark.kml'))
When using the command View(matrix) or View(dataframe) or by doubleclicking in Rstudio on the Data in the global environment, a screen shows up in which you can see your data. However, when scrolling down on that screen the column names dissappear. Is there a "freeze panes" option as in excel?
Thanks
I find gvisTable from package googleVis quite convenient when viewing data in RStudio.
"The gvisTable function reads a data.frame and creates text output referring to the Google Visualisation API, which can be included into a web page, or as a stand-alone page. The actual chart is rendered by the web browser."
gvisTable opens a viewer pane in RStudio (where local web content can be viewed). The headers are always visible and there are several options that allow you to customize the view. You can sort by variables by clicking on their header.
A simple example:
library(googleVis)
gt <- gvisTable(iris)
plot(gt)
gt <- gvisTable(iris, options = list(page = 'enable', height = 200))
plot(gt)
Follow up from :
https://groups.google.com/forum/#!topic/shiny-discuss/u7gwXc8_vyY
I have the exact same R Shiny structured program as the user in the post, except I am using the googleVis Shiny package for my plots. For example, here is a plot of a gVis table:
output$gvisTable <- renderGvis( {
if (is.null(dataset))
return(NULL)
gvisTable(dataset)
})
EDIT:
My code to save ggplots:
server.R
name <- paste0(input$filename, ".png")
print(p)
if(input$savePlot) {
ggsave(name, p, type="cairo-png")
}
ui.R (in sidePanel)
wellPanel(
textInput('filename', "Filename"),
checkboxInput('savePlot', "Check to save")
)
This is what I am using to try to save gVis plots:
name <- paste0(input$filename, ".png")
if(input$savePlot) {
png(name, *INPUT GVIS PLOT HERE*, type="cairo-png")
dev.off()
}
This does not work: I get the error: 'non-numeric argument to binary operator'
I can't find a way to allow the user to download a gVis plot. I can't use the method in the linked post because you cannot 'print' a gVis plot.
Also, the files are locally saved to my R working directory, but I plan to upload this app to the web. Where would the files be saved for the user? Ideas?
I see no png method documented for gvis objects.
There are two ways to "print" documented in the help page linked from the googleVis main Index page for print.gvis. The default method (when the tag is NULL or "html") is to send a Java script page to your browser. The other (when you set tag="chart" is to construct an html file with the name you give it. I suppose you could arrange something with system commands sent to a running instance of a particular browser, but for that you should use different SO tags so that you attract the interest of people using the same software as you. (I'm using a Mac with Firefox and having no difficulties seeing the "printed" output.) If you plan to "upload it to the web", then you need to have a server. Is my impression this is a bit new for you correct?
print(GTM, tag="chart", file="test.html")
#created in my working directory
In the world of the R statistics package, rgl allows me to generate 3d plots that I can rotate with my mouse. Is there a way I can export these plots in a portable format, load them in a web browser or other third party tool and rotate them there? I Am especially interested in the web browser solution since this will allow me to share the plots on an internal wiki.
If rgl does not allow this, are there other libraries or strategies that would allow me to accomplish this?
You could try the vrmlgen package. It will produce 3d VRML files that can be displayed with a browser plugin; you can find a plugin at VRML Plugin and Browser Detector.
Once you've installed a plugin, try this:
require(vrmlgen)
example(bar3d)
NB: the example code didn't automatically open in a browser for me (RStudio, Win7, Chrome) because the path got mangled. You might need to use:
require(stringr)
browseURL(str_replace_all(file.path(outdir, 'barplot.html'), fixed('\\'), '/'))
If you don't want to install a VRML plugin, you could use X3DOM instead. You'll need a converter, but your users should be able to view them with just a (modern) browser. You might have to modify the following code to get the paths right:
setwd(outdir)
aopt <- 'C:/PROGRA~1/INSTAN~1/bin/aopt' # Path to conversion program
vrml <- 'barplot.wrl'
x3dom <- 'barx.html'
command <- paste(aopt, '-i', vrml, '-N', x3dom)
system(command)
# LOG Avalon Init: 47/616, V2.0.0 build: R-21023 Jan 12 2011
# LOG Avalon Read url
# LOG Avalon Read time: 0.074000
# ============================================
# Call: writeHTML with 1 param
# Write raw-data to barx.html as text/html
# WARNING Avalon Run NodeNameSpace "scene" destructor and _nodeCount == 3
# WARNING Avalon Try to remove nodes from parents
# WARNING Avalon PopupText without component, cannot unregister
# WARNING Avalon Avalon::exitSystem() call and node/obj left: 0/3331
browseURL(file.path(outdir, 'barx.html'))
setwd(curdir)
For a simple solution try this...
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
plot3d(x,y,z,
col=rainbow(1000),
type = "s",
size=1,
xlab = "x",
ylab = "y",
zlab = "z",
box=T)
# This writes a copy into temporary directory 'webGL', and then displays it
browseURL(paste("file://", writeWebGL(dir=file.path("C:/Your-Directory-Here/", "webGL"), width=700), sep=""))
open the index.html file in Firefox or similar browser that supports HTML5 and WebGL
Pete's suggestion is worth the bounty. The wrl-detour is not really necessary, it is rather easy to generate the xml-file with sprintf and friends.
The problem is speed: As a comparison, I had a color-code stomach MRI with 17000 spheres (for voxels), which was quite responsive on my screen with rgl.
When I ported it to x3dom, the system froze. A reduced set with 450 spheres works:
http://www.menne-biomed.de/uni/x3dsample.html
Browser support is inconsistent. Some of the samples on the x3dom example page work best with (believe it or not) Internet Explorer + Flash 11. Check the dynamic light example.
My example works, but looks flat on Firefox 7.0.1. Best is always Chrome.
Added later:
Here is another example:
Stomach3D as Zip
The x3d file contained in it can be displayed even with on-board graphics using the Instant Reality Viewer. The html file generated from it sometimes loads, but cannot be rotated.
For ultimate flexibility, I've had great luck using Processing. It was originally written in java, but has now been stably ported to javascript, and more experimentally to python and even a few others.
http://processingjs.org
http://processing.org
It uses the HTML5 <canvas> element to process your Processing code on-the-fly. You can either link to your visualization code in another file, or write it right in your html file (reminds me of Sweave!).
Also, there is a huge resource of open source examples online. For example:
http://openprocessing.org
Lastly, here is a gist I put together to demonstrate the basic setup. Just download the processing.js file into the same folder as the gist and open up your browser.
https://gist.github.com/1295842
It'll look like this:
A couple of million years ago (OK, 2005) I wrote R code to dump graphics primitives in Mathematica (!!) graphics format, which could then be embedded and viewed with the LiveGraphics3D Java plug-in. I haven't tried to use it in 6 years, but I could try to resurrect it if there were interest.
PS here are the results of help(package="LG3d"):
get.live.jar Download live.jar Java archive
LG.display Display Live3D graphics in a browser
LG.html.head header and footer files for LiveGraphics HTML
files
LGmobius Draw a 3D mobius strip
LG.open open and close LiveGraphics3D files
LG.plot.profiles Plot likelihood surface + profiles using
Live3D
LGtorus Draw a torus in LG graphics system
LGtoruswrap Utility functions for LGtorus
mma.brace Low-level graphics primitives for
LiveGraphics3D
mma.edge change edge style
mma.persp Output a perspective plot to a LiveGraphics3D
file
mma.point Medium-level graphics primitives for
LiveGraphics3D
mma.polygon draw a Mma/LG3d polygon
The rgl package now hast the rglwidget function, which is probably the cleanest and easiest method to create widgets of rgl plots.