I`m working with RMarkdown and Python, I just created a chunk where I add code relate to the folium library, but I can create the report or show up the map
Chunk setup in my RMarkdown Report, I`m al so working with matplotlib in the same RMarkdown report a nd it works fine
```{r setup,include=FALSE}
library(reticulate)
library(ggplot2)
library(lattice)
library(vembedr)
use_python("C:/Users/renzocrossi/AppData/Local/Programs/Python/Python310/python.exe")
knitr::opts_chunk$set(echo=TRUE,message = FALSE,warning = FALSE)
This is the code in the RMarkdown chunk about folium
```{python}
import folium
m = folium.Map(location = [46.20, 6.144], zoom_start=6, tiles="OpenStreetMap")
fg = folium.FeatureGroup(name="My Map")
fg.add_child(folium.Marker(location=[40.12, 10.1], popup="Hi I'am a Marker",
icon=folium.Icon(color='green')))
m.add_child(fg)
m
```
<folium.folium.Map object at 0x000001F6A1098B20>
I ran the code in Python and didn't get an output either. The only way that I think this would work as-is is in a Jupyter notebook. (I think!)
However, with just a bit more, you can definitely get the map on the document. I added import webbrowswer so that I could export the map as HTML, then render it in R Markdown.
```{python mapper, include=FALSE}
import folium
import webbrowser
m = folium.Map(location = [46.20, 6.144], zoom_start=6, tiles="OpenStreetMap")
fg = folium.FeatureGroup(name="My Map")
fg.add_child(folium.Marker(location=[40.12, 10.1], popup="Hi I'am a Marker",
icon = folium.Icon(color='green')))
m.add_child(fg)
m.save("map.html")
webbrowser.open("map.html")
```
Then outside of the Python chunk (not in any chunk), I called the map.
![](map.html)
![](map.html){width=100% height=800px}
I don't know if you have any default figure sizes set, I didn't for this example. However, the calls of this map rendered this:
By the way, the maps are still completely interactive, as they would be in Python or if rendered directly through R.
For example, I decreased magnification and rendered the following:
Related
I want to create world maps using folium within a text editor (geany), not using notebooks. this piece of code will work but i cant see the output. i.e, the actual map. How do i get it to display the map.
import pandas as pd
import numpy as np
import folium
m = folium.Map(location=[40.0150, -105.2705])
# Display the map
m
You can use import webbrowser and open the saved html file in your browser.
import folium
import webbrowser
m = folium.Map(location=[40.0150, -105.2705])
m.save("map.html")
# Display the map
webbrowser.open("map.html")
Just like yabberth said save the map as map.html after saving html call the system command like os.system('map.html')
I'm working with a map created using python, folium, and geojson, similar to this one.
However, instead of this image being an interactive HTML document, I would rather simply export it to png or svg.
Using the syntax:
m = folium.Map( # etc..)
m.save("filename.png")
Saves a file, but it is still HTML, rather than png. What's the correct output command to render not-to-html?
I use this:
... where m is my map object.
And 5 is the time (seconds) to render the map.
import io
from PIL import Image
img_data = m._to_png(5)
img = Image.open(io.BytesIO(img_data))
img.save('image.png')
I really like how folium works with python on jupyter notebooks (I haven't tried it, but judging from the tutorials). What I want to achieve is same functionality, but with zeppelin notebooks using spark.ipyspark. Folium functionality would be huge improvement of data plotting capabilities of zeppelin's notebooks.
What I tried is simple:
import folium
m = folium.Map(location=[45.5236, -122.6750])
m
This is only returning <folium.folium.Map at 0x10f4a3518>
What I tried next is to build HTML map, save it locally and then invoke it as output of zeppelin paragraph.
import folium
from IPython.display import HTML
from IPython.display import IFrame
m =folium.Map(
location=[45.5236, -122.6750],
tiles='Stamen Toner',
zoom_start=13
)
m.render_iframe = True
m.save('/Users/abc/m.html')
HTML("<iframe src=file:///Users/abc/m.html width=700 height=350></iframe>")
Which again gave me:
<IPython.core.display.HTML object>
Then I exchanged last row with:
IFrame("src=file:///Users/abc/m.html", width=700, height=350)
Which again:
<IPython.lib.display.IFrame at 0x112882c88>
When I try python's print using:
print("%html <iframe src=file:///Users/abc/m.html width=700, height=350></iframe>")
I get 700x350 blank white window as output of the paragraph. When I try to change src to for example "https://zeppelin.apache.org/" it works well.
I feel like two things are not working properly.
1. Folium module with zeppelin notebook which is not invoking map properly.
2. Showing local HTML page as output of zeppelin paragraph.
Does anybody tried this already? Was anybody successful to overcome this?
Thanks for advice, I was able to run it by adding:
html_string = m.get_root().render()
print("%html", html_string)
So now entire code looks like:
import folium
m =folium.Map(
location=[45.5236, -122.6750],
tiles='Stamen Toner',
zoom_start=13,
width=600,height=300
)
html_string = m.get_root().render()
print("%html", html_string)
EDIT:
using above described way was modifying appearance of entire zeppelin notebook. I used different method, using html_string = m._repr_html_(),which is according this link (github.com/python-visualization/folium/issues/781) used in jupyter for showing HTML in iframe.
So code now:
import folium
m =folium.Map(
location=[45.5236, -122.6750],
tiles='Stamen Toner',
zoom_start=13,
width=600,height=300
)
html_string = m._repr_html_()
print("%html", html_string)
I have a huge grid in *.pvd format. I would like to ensure some cells size specification have been respected when building said grid. To do so, I should get a cell data array with (dx,dy,dz)
I first tried to check this in Paraview with very little success. Then I resolved to export the mesh in various format (vtk, vtu, ex2) and import things into python using the vtk module, as in the code below. Unfortunately, the size of the mesh forbids it and I get various error messages stating "Unable to allocate n cells of size x".
import vtk
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("my_mesh.vtu")
reader.Update()
Finally, in Paraview there is a python-shell that allows me to open the grid file in either pvd or vtk format:
>>> from paraview.simple import *
>>> my_vtk = OpenDataFile("my_mesh.vtk")
>>> print dir(my_vtk)
Despite my browsing the methods and attribute of this reader object, I remain clueless about where to fetch any geometry information on the grid. I also browsed through the simple module documentation and I can't really wrap my head around it.
So how can one retrieve information regarding the geometry of cells from a paraview.servermanager.LegacyVTKReader object?
Any clue about how to achieve this with through the paraview GUI, or any kludge to load the vtk object into python vtk despite the memory issue is also very welcome. Sorry for such a hazy question, but I don't really know where to get started...
You can use GetClientSideObject() (see here) to get a VTK object in the Paraview Python shell. After that you can use all the regular VTK Python functions. For example, you can write the following in the Paraview Python shell
>>> from paraview.simple import *
>>> currentSelection = GetActiveSource()
>>> readerObj = currentSelection.GetClientSideObject()
>>> unstructgrid = readerObj.GetOutput()
>>> firstCell = unstructgrid.GetCell(0)
>>> cellPoints = firstCell.GetPoints()
Alternatively, you can use Programmable Filter in ParaView. This allows access to full VTK python module and even NumPy or other modules. You can enter following script in the script window of the programmable filter:
import vtk as v
import numpy as np
inp = self.GetUnstructuredGridInput()
cells = inp.GetCells()
cells.InitTraversal()
cellPtIds = v.vtkIdList()
lenArr = v.vtkDoubleArray()
lenArr.SetNumberOfComponents(3)
lenArr.SetName('CellSize')
while cells.GetNextCell( cellPtIds ):
pts = []
for i in range( cellPtIds.GetNumberOfIds() ):
ptCoords = inp.GetPoint( cellPtIds.GetId(i) )
pts.append( ptCoords )
pts = np.array( pts )
dx = np.max(pts[:,0]) - np.min(pts[:,0])
dy = np.max(pts[:,1]) - np.min(pts[:,1])
dz = np.max(pts[:,2]) - np.min(pts[:,2])
lenArr.InsertNextTuple3(dx, dy, dz)
out = self.GetUnstructuredGridOutput()
out.ShallowCopy( inp )
out.GetCellData().AddArray( lenArr )
In Paraview when you select the 'ProgrammableFilter1' icon in your pipeline, a new cell data array will be available to you from the drop-down as shown in the screenshot below. You can modify the script above to save the data to file to analyze externally.
This information is visible in the Information Tab.
I am following the documentation for rpy2 here (http://rpy.sourceforge.net/rpy2/doc-2.1/html/graphics.html?highlight=lattice). I can successfully plot interactively using lattice from rpy2, e.g.:
iris = r('iris')
p = lattice.xyplot(Formula("Petal.Length ~ Petal.Width"),
data=iris)
rprint = robj.globalenv.get("print")
rprint(p)
rprint displays the graph. However, when I try to save the graph to pdf by first doing:
r.pdf("myfile.pdf")
and then my lattice calls, it does not work and instead results in an empty pdf. If I do the same (call r.pdf, then plot) with ggplot2 or with the R base, then I get a working pdf. Does lattice require anything special from within Rpy2 to save the results to a PDF file? The following does not work either:
iris = r('iris')
r.pdf("myfile.pdf")
grdevices = importr('grDevices')
p = lattice.xyplot(Formula("Petal.Length ~ Petal.Width"),
data=iris)
rprint = robj.globalenv.get("print")
rprint(p)
grdevices.dev_off()
Thank you.
you need some equivalent of dev.off() after the print command.
That is, in order to save your graphs to pdf, the general outline is:
pdf(...)
print(....)
dev.off()
Failing to call dev.off() will result in an empty pdf file.
from this source, it appears that the equivalent in rpy2 might be
grdevices.dev_off()
The solution is to use:
robjects.r["dev.off"]()
For some reason the other variants do not do the trick.