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?
Related
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")
I am trying to work on a US map in R. I have done it a lot of times but this time it gives me this error when I try to load:
us<- map_data("state")
Error in .C(C_map_type, as.character(mapbase), integer(1)) :
Incorrect number of arguments (2), expecting 0 for ''
I have ggmap and ggplot2 libraries loaded. Where am I going wrong?
You need the 'maps' package along with ggmap.
library(maps)
library(ggmap)
us<- map_data("state")
This should work
It looks like there are bugs in tidyverse which interferes with ggplot2 maps functionality. See this related question.
This works in a clean, freshly-restarted R session:
us <- ggplot2::map_data("state")
However, this does not:
library(tidyverse)
us2 = ggplot2::map_data("state")
I'm unable to save a plot generated by the plot.Node function in data.tree. I've tried the following:
### Create tree object and plot it
data(acme);
plot(acme);
This works fine, showing the plot, as one would expect.
### Try saving it as png
png(filename='file.png', type='cairo-png');
plot(acme);
dev.off();
This creates an empty file. ggsave does the same. Apparantly, plot.Node uses DiagrammeR under the hood, so I looked into that package. It has a function to export graphs:
export_graph(acme, file_name="file.png");
This gives the error:
Error in file.exists(diagram) : invalid 'file' argument
When I transform to GraphViz first, I get a different error:
export_graph(ToGraphViz(acme), file_name="file.png");
Error in graph$dot_code : $ operator is invalid for atomic vectors
Clearly, exporting to GraphViz doesn't quite export to what DiagrammeR expects.
I'm in RStudio and so could in theory just save the plot using the GUI, but I need this for in a script.
Apparently, plot.Node doesn't actually plot anything - instead it seems to generate html/js. Does this mean that that result cannot be stored as a graphic? Or is there some export/conversion function somewhere that I'm completely missing? it certainly feels like I'm missing something obvious - I assume the need to store plotted data.trees as images is quite common. But I have no idea which potential solutions I can still explore.
I'd be very grateful for any pointers anybody has!
As sebastian-c suggested, things work now a bit differently than suggested by Matherion, as of R 3.3.3 with data.tree 0.7.0 and DiagrammeR 0.9.0
Pre-requisite: DiagrmmeRsvg and dependencies need to be installed. Depending on your OS, for this to work you might have to install V8. For example on ubuntu:
apt-get install libv8-3.14-delibv8-3.14-dev
And then in R:
install.packages("DiagrammeRsvg")
On Windows, I didn't have to install anything (maybe because Chrome is installed?).
Once DiagrammeRsvg is available, run:
library(data.tree)
data(acme)
library(DiagrammeR)
export_graph(ToDiagrammeRGraph(acme), "export.pdf")
I've found the answer, at least, partially. There exists a package dedicated to exporting GraphViz diagrams to SVG: DiagrammeRsvg.
So this works:
treeAsSVG <- export_svg(grViz(ToGraphViz(acme)));
writeLines(treeAsSVG, "filename.svg"));
The grViz is necessary to actually convert the ToGRaphViz output to something that can be interpreted by export_svg. I'm still not really sure (yet) what all goes on under the hood - for example, this does not work:
export_graph(grViz(ToGraphViz(acme)), file_name="filename.svg");
But, if anybody else has a similar problem and stumbles upon this question, perhaps this partial answer can help them to at least export something that can then be integrated in e.g. html pages.
By converting acme with as.phylo() it works, but it looks a little boring:
plot(as.phylo(acme),
show.node.label=TRUE,
node.pos=2,
no.margin=TRUE
)
# adding edge labels
edgelabels(as.vector(acme$Get("cost"))[-1],
adj = c(0,-0.5),
frame = "none")
solution with as.phylo()
I also tried as.igraph. However, the nodes overlap and it looks even less pretty:
plot(0, type="n", ann=FALSE, axes=FALSE,
xlim=extendrange(ig[,1]),
ylim=extendrange(ig[,2]))
plot(ig,
layout=layout_as_tree(ig,root=1),
vertex.shape="rectangle",
vertex.size=(strwidth(V(ig)$name) + strwidth("oo")) * 100,
#vertex.size2=strheight("I") * 2 * 100,
edge.label=acme$Get("p",traversal = "level")[-1]
)
solution with as.igraph()
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")
I am having an issue with the R package Rgooglemaps. I can retrieve a map from google maps or open street map but the PlotOnStaticMap function does not overlap the data I want to plot to the map. Instead it opens a new graphical device where it plots the data. So I end up with:
an image saved in my working dir which contains only the retrieved google map
a R graphic device window with my data plotted over a white background.
I am on windows, using R version 2.13.1 and RGUI. The issue appears also when I run the code via command line. I remember I used Rgooglemaps a few months ago and it worked properly for me. Meanwhile I upgraded my R version, so it could be a version related issue. Can someone give it a try and see if you have the same issue (and a way to solve it)? Here an example to reproduce the issue (taken from http://www.r-bloggers.com/visualizing-gis-data-with-r-and-open-street-map/). The example is using Open Street Map instead of googlemaps but the behavior is the same.
The code:
require(RgoogleMaps)
lat_c<-51.47393
lon_c<-7.22667
bb<-qbbox(lat = c(lat_c[1]+0.01, lat_c[1]-0.01), lon = c(lon_c[1]+0.03, lon_c[1]-0.03))
OSM.map<-GetMap.OSM(lonR=bb$lonR, latR=bb$latR, scale = 20000, destfile="bochum.png")
image(OSM.map)
lat<- c(51.47393, 51.479021)
lon<- c(7.22667, 7.222526)
val <- c(0, 255)
lat_adj<-function(lat, map){(map$BBOX$ll[1]-lat)/(map$BBOX$ll[1]-map$BBOX$ur[1])}
lon_adj<-function(lon, map){(map$BBOX$ll[2]-lon)/(map$BBOX$ll[2]-map$BBOX$ur[2])}
PlotOnStaticMap(OSM.map, lat = lat_adj(lat, OSM.map), lon = lon_adj(lon, OSM.map),
col=rgb(255,0, val,90,maxColorValue=255),pch=16,cex=4)
dev.print(jpeg,"test.jpeg", width=1204, height=644, units="px")
I've only re-run your code, and not looked into the problems and get the error message:
dev.print(jpeg,"test.jpeg", width=1204, height=644, units="px")
windows
2
Error: REAL() can only be applied to a 'numeric', not a 'NULL'
I ran the above code on R2.14.0 and everything appears to work.