Giter Club home page Giter Club logo

mplleaflet's Introduction

mplleaflet

mplleaflet is a Python library that converts a matplotlib plot into a webpage containing a pannable, zoomable Leaflet map. It can also embed the Leaflet map in an IPython notebook. The goal of mplleaflet is to enable use of Python and matplotlib for visualizing geographic data on slippy maps without having to write any Javascript or HTML. You also don't need to worry about choosing the base map content i.e., coastlines, roads, etc.

Only one line of code is needed to convert a plot into a web map. mplleaflet.show()

The library is heavily inspired by mpld3 and uses mplexporter to do most of the heavy lifting to walk through Figure objects.

Examples

Basic usage

The simplest use is to just create your plot using matplotlib commands and call mplleaflet.show().

>>> import matplotlib.pyplot as plt
... # Load longitude, latitude data
>>> plt.hold(True)
# Plot the data as a blue line with red squares on top
# Just plot longitude vs. latitude
>>> plt.plot(longitude, latitude, 'b') # Draw blue line
>>> plt.plot(longitude, latitude, 'rs') # Draw red squares

matplotlib x,y plot

Normally, displaying data as longitude, latitude will cause a cartographer to cry. That's totally fine with mplleaflet, Leaflet will project your data properly.

# Convert to interactive Leaflet map
>>> import mplleaflet
>>> mplleaflet.show()

Click to view final web page

Leaflet map preview

Disclaimer: Displaying data in spherical mercator might also cause a cartographer to cry.

show() allows you to specify different tile layer URLs, CRS/EPSG codes, output files, etc.

IPython Notebook embedding

Just use mplleaflet.display() to embed the interactive Leaflet map in an IPython notebook. Click here to see a live example.

Other examples

Why mplleaflet?

Other Python libraries, basemap and folium, exist to create maps in Python. However mplleaflet allows you to leverage all matplotlib capability without having to set up the background basemap. You can use plot() to style points and lines, and you can also use more complex functions like contour(), quiver(), etc. Furthermore, with mplleaflet you no longer have to worry about setting up the basemap. Displaying continents or roads is determined automatically by the zoom level required to view the physical size of the data. You should use a different library if you need fine control over the basemap, or need a geographic projection other than spherical mercator.

Installation

Install mplleaflet from PyPI using $ pip install mplleaflet.

Development

If developing for mplleaflet, mplexporter is a git submodule with its Python package files placed under the mplleaflet package. The Makefile copies the files into the appropriate location.

$ git submodule init
$ git submodule update
$ make
$ pip install -e .

Dependencies

Optional

  • pyproj Only needed if you only use non-WGS-84 projections.
  • GeoPandas To make your life easier.

mplleaflet's People

Contributors

bibmartin avatar disarticulate avatar jwass avatar mariusvniekerk avatar michelleful avatar mnfienen avatar ocefpaf avatar schmudo avatar smnorris avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mplleaflet's Issues

Default tile server is overloaded

The default osm tile server is overloaded and kind of slow. So some extra tile servers and better doku on how to change the tile server would be nice

mplleaflet.show() doesn't work

I have 2 versions of python (2.7 and 3.5). On both the mplleaflet is installed. But once import it into my project, it comes but later says 'import resolves to its containing file' and even the show() function doesnt work. It says module 'mplleaflet' has no attribute 'show'. Could you please help me with this. your feature is good and I want to use the lat and long gps data of my bike ride.

Contourf opacity level when plotted on the map

I was able to plot 2D array data on the map with the contourf method from matplotlib, although, the opacity level is too low even if I set alpha to the maximum value. I'd like to know if there is any specific reason for that to happen.
This is how it looks on the library map:

screenshot from 2018-02-02 10-58-33

And this how it looks on a regular basemap instance:
figure_1

My guess is that the library on its own decrease the opacity so it can show the map details under the filled contour when it is opened, if so, how could I bypass this? I need the max opacity level.

Dynamically update the Map

Hello,

I want to update the map dynamically.
For example, I have a stream of coordinates coming in and want to plot them on the map, one after the other.
Is this possible with mplleaflet?

popup window

It would be nice to have a popup window from the label property set from a mpl.scatter call ?

The bindPopup method from Leaflet is there to do so.
Telling that, not sure to know how to do it.

Can't plot a circle with add_artist

I'm trying to plot a fixed-size circle on a map.

(By "fixed-size", I mean that this circle is not a marker, it shouldn't adapt to the zoom level, but should stay of, say, 25m diameter whatever the zoom level).

Here is what I got :

import mplleaflet
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()
x = 2.363561
y = 48.951918
r = 20
circle1 = mpl.patches.Circle((x,y), radius=r)
circle2 = plt.Circle((x, y), r)

ax.add_artist(circle1)
ax.add_artist(circle2)

mplleaflet.show(fig = ax.figure)

Code runs fine, but when the new leaflet tab opens, I got nothing but a full map of the world, and no circle :

image

Stack overflow related question : https://stackoverflow.com/questions/46305778/plotting-a-circle-in-leaflet-using-add-artist

Does not work with DiGraph (networkx)

mplleaflet version: 0.0.5

import mplleaflet
import networkx as nx
import matplotlib.pyplot as plt

pos = {u'Afghanistan': [66.00473365578554, 33.83523072784668],
 u'Aland': [19.944009818523348, 60.23133494165451],
 u'Albania': [20.04983396108883, 41.14244989474517],
 u'Algeria': [2.617323009197829, 28.158938494487625]}

G = nx.DiGraph() # does not work with DiGraphs

fig, ax = plt.subplots()
G.add_edge('Afghanistan','Aland')
G.add_edge('Albania','Algeria')

nx.draw_networkx_nodes(G,pos=pos,node_size=10,node_color='red',edge_color='k',alpha=.5, with_labels=True)
nx.draw_networkx_edges(G,pos=pos,edge_color='gray', alpha=.1)
nx.draw_networkx_labels(G,pos, label_pos =10.3)

mplleaflet.display(fig=ax.figure)

The example works with Graphs but not with DiGraphs. I get the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-9c14f555d863> in <module>()
     18 nx.draw_networkx_labels(G,pos, label_pos =10.3)
     19 
---> 20 mplleaflet.display(fig=ax.figure)

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\_display.py in display(fig, closefig, **kwargs)
    151         plt.close(fig)
    152 
--> 153     html = fig_to_html(fig, **kwargs)
    154 
    155     # We embed everything in an iframe.

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\_display.py in fig_to_html(fig, template, tiles, crs, epsg, embed_links)
     82     renderer = LeafletRenderer(crs=crs, epsg=epsg)
     83     exporter = Exporter(renderer)
---> 84     exporter.run(fig)
     85 
     86     attribution = _attribution + ' | ' + tiles[1]

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\mplexporter\exporter.py in run(self, fig)
     49             import matplotlib.pyplot as plt
     50             plt.close(fig)
---> 51         self.crawl_fig(fig)
     52 
     53     @staticmethod

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\mplexporter\exporter.py in crawl_fig(self, fig)
    116                                        props=utils.get_figure_properties(fig)):
    117             for ax in fig.axes:
--> 118                 self.crawl_ax(ax)
    119 
    120     def crawl_ax(self, ax):

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\mplexporter\exporter.py in crawl_ax(self, ax)
    136                     self.draw_text(ax, artist)
    137             for patch in ax.patches:
--> 138                 self.draw_patch(ax, patch)
    139             for collection in ax.collections:
    140                 self.draw_collection(ax, collection)

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\mplexporter\exporter.py in draw_patch(self, ax, patch, force_trans)
    225                                 pathcodes=pathcodes,
    226                                 style=linestyle,
--> 227                                 mplobj=patch)
    228 
    229     def draw_collection(self, ax, collection,

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\leaflet_renderer.py in draw_path(self, data, coordinates, pathcodes, style, offset, offset_coordinates, mplobj)
    123             else:
    124                 data = [c.tolist() for c in data]
--> 125             rings = list(iter_rings(data, pathcodes))
    126 
    127             if style['facecolor'] != 'none':

~\Anaconda3\envs\gis\lib\site-packages\mplleaflet\utils.py in iter_rings(data, pathcodes)
     12             ring.append(point)
     13         else:
---> 14             raise ValueError('Unrecognized code: {}'.format(code))
     15 
     16     if len(ring):

ValueError: Unrecognized code: S

Dynamic tile creation

We've used leaflet in the past on running servers that dynamically generated tiles from sparse image format files. It would be really nice if this could be possible with mplleaflet, although I'm not certain it is possible with the IPython architecture. What this might look like would be defining a function (essentially a URL handler) that received the x and y map tile indices and the level of detail, and returned a PNG. It may be possible, but I don't know how to attach a URL handler to the IPython notebook. Is this feasible to do within mplleaflet?

Is it possible to set the opacity of a plot?

mplleaflet seems to respect most of the options you can set on a matplotlib plot, except for one crucial one, which is opacity. That is, at least AFAIK.

Am I wrong (in that case, what's the parameter name!)? If not, then I believe that such a control should be made a feature.

Polygons are distorted

When plotting a regular polygon, it gets distorted on the map. My guess is that it's because the radius is evaluated as degrees, and 1 degree in latitude is not the same distance as 1 degree in longitude (except at latitude = 0 of course) :

import mplleaflet
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()
lon = 2.363561
lat = 48.951918
r = 20
regpol1 = mpl.patches.RegularPolygon((lon, lat), 16, radius=r, color = 'r')
ax.add_patch(regpol1)

mplleaflet.show(fig = ax.figure)

image

Same thing with lat = 0 => no distortion :

image

Additional documentation for contour.py example

I have been using mplleaflet successfully in other contexts (and it's great!) but just wanted to suggest a small modification (or additional documentation to) the contour.py so that new users like myself can reproduce the results.

I (and independently a friend) have not been able to get the contour.py example to work. We loaded rain data from the listed source into the geodataframe and got matplotlib.contour plot to correctly display in an ipython notebook. However when we make the last mplleaflet.show call the browser window displays only the basemap with no sign of the contour plot.

The contour.py module does mention that the CRS info has been only 'gleaned from reading the NWS and Proj.4 docs' but someone seems to have made it work to produce the example map that you link to in the README.

The data we downloaded is more recent precipitation data than in the example (the last file I downloaded was "nws_precip_year2date_observed_20150101.shp" whereas in the example it is "'nws_precip_year2date_observed_20140406.shp"). I don't think the CRS would change but perhaps it has. I can't see what else we are doing wrong since we are following the contour.py code practically verbatim.

So my suggestion is to either add documentation to give users more guidance on how to 'glean' the CRS themselves (if that is the problem) or perhaps easier and more effective: modify the example to work with another fixed dataset (with a known CRS) to be sure it works everytime. Thanks.

Support for plt.text

Attempting to use mplleaflet.show() on a matplotlib plot with text() objects added, causes a NotImplemented exception.

Documentation

Hi, thanks for the great package.

Is there a place where I can find what are the options I can pass into **kwargs to change the look of the maps?

Make style configurable

Allow different types of styles (feature properties) for different conversion types. simplestyle-spec?

Not JSON serializable

When attempting to plot matplotlib path and line collection I get the error "TypeError: Object of type 'int64' is not JSON serializable" because the collection is a numpy array.

I am able to fix this manually with a tolist() argument in the _display() module.

Was wondering if this will be addressed in a future release?

Thanks

Modify opacity of background map

I am using mplleaflet to display an scatter of points in a map. Is there any method to decrease the opacity level of the background map? So far I have achieved it manually by modifying the leaflet.css file line 137 "opacity: 1;" to the value I want, 0.5 for example. However I need to create a huge number of maps so setting it manually is not practical.

I also tried passing the alpha argument when creating the axes on the mpl figure, but does not work. The alpha value for each point I draw does work. But I want to modify the opacity for the base map, not the points I am drawing.
I also tried modifying the CSSLink directing to the leaflet.css file. I made my own copy of the file with the (fixed) value of opacity desired, however it does not work since the map construction with the new CSSLink is not correctly rendered.

Any help will be appreciated.

Animations?

Hi,

Is it possible to somehow make animations on OpenStreetMap using mplleaflet?

Any suggestions on how to achieve this, including adding/modifying the code would be helpful :)

Upload to PyPI

Hello,

I really like this project but could you please push it on pypi? it would help installation on our part.
Thanks

Contour Labels

Feature Request: Would like to see the ability to display contour labels, similar to Matplotlib.

contourf error

Hi,
Really great work it's an amazing tool. I managed to make the contour example work and one of my contour plot also. But when I switch the plot to contourf (wich is ok with my plt.show()), mplleaflet crashes with this error :

Traceback (most recent call last):
  File "readnc_kb.py", line 37, in <module>
    mplleaflet.show(path='test.html')
  File "/usr/lib/python2.7/site-packages/mplleaflet/_display.py", line 180, in show
    save_html(fig, fileobj=f, **kwargs)
  File "/usr/lib/python2.7/site-packages/mplleaflet/_display.py", line 131, in save_html
    html = fig_to_html(fig, **kwargs)
  File "/usr/lib/python2.7/site-packages/mplleaflet/_display.py", line 84, in fig_to_html
    exporter.run(fig)
  File "/usr/lib/python2.7/site-packages/mplleaflet/mplexporter/exporter.py", line 51, in run
    self.crawl_fig(fig)
  File "/usr/lib/python2.7/site-packages/mplleaflet/mplexporter/exporter.py", line 118, in crawl_fig
    self.crawl_ax(ax)
  File "/usr/lib/python2.7/site-packages/mplleaflet/mplexporter/exporter.py", line 140, in crawl_ax
    self.draw_collection(ax, collection)
  File "/usr/lib/python2.7/site-packages/mplleaflet/mplexporter/exporter.py", line 272, in draw_collection
    mplobj=collection)
  File "/usr/lib/python2.7/site-packages/mplleaflet/mplexporter/renderers/base.py", line 272, in draw_path_collection
    mplobj=mplobj)
  File "/usr/lib/python2.7/site-packages/mplleaflet/leaflet_renderer.py", line 125, in draw_path
    rings = list(iter_rings(data, pathcodes))
  File "/usr/lib/python2.7/site-packages/mplleaflet/utils.py", line 14, in iter_rings
    raise ValueError('Unrecognized code: {}'.format(code))
ValueError: Unrecognized code: Z

Any ideas ?

Release

Can you push new version to PyPl?
Current version does not work correctly with python3 (because of basestring reference).

Fix CSS in embedded IPython notebook

The +/- buttons look like normal, underlined links.

This could be due to the setTimeout() being used for the notebooks. That should probably be replaced with the proper Javascript callbacks.

screen shot 2014-05-05 at 8 38 23 am

Error when trying to plot a circle with add_patch

I'm still trying to display a circle of fixed size in a leaflet map.

I tried with .add_artist() (see here) and I'm now trying with .add_patch(). Here is what I'm doing :

import mplleaflet
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()
x = 2.363561
y = 48.951918
r = 20
circle1 = mpl.patches.Circle((x,y), radius = r)
circle2 = plt.Circle((x, y), r)

#ax.add_patch(circle1)
#ax.add_patch(circle2) 

mplleaflet.show(fig = ax.figure)

You can try to uncomment one of the two commented lines, it doesn't matter which line is uncommented, the same error pops.

Here is the trace I get :

Traceback (most recent call last):

  File "<ipython-input-81-1fdd7f4a9d12>", line 16, in <module>
    mplleaflet.show(fig = ax.figure)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 180, in show
    save_html(fig, fileobj=f, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 131, in save_html
    html = fig_to_html(fig, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\_display.py", line 84, in fig_to_html
    exporter.run(fig)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 51, in run
    self.crawl_fig(fig)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 118, in crawl_fig
    self.crawl_ax(ax)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 138, in crawl_ax
    self.draw_patch(ax, patch)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\mplexporter\exporter.py", line 227, in draw_patch
    mplobj=patch)

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\leaflet_renderer.py", line 125, in draw_path
    rings = list(iter_rings(data, pathcodes))

  File "C:\ProgramData\Anaconda3\lib\site-packages\mplleaflet\utils.py", line 14, in iter_rings
    raise ValueError('Unrecognized code: {}'.format(code))

ValueError: Unrecognized code: C

Related SO question : https://stackoverflow.com/questions/46341560/cant-display-patches-with-mplleaflet

=============================

Just to see what would happen, I tried doing the same thing than this, which is changing

elif code == 'L': ring.append(point)

to

elif code == 'L' or code == 'Z' or code == 'S' or code == 'C': ring.append(point)

in mplleaflet\utils.py", line 11 and 12. Here is what I got :

image

Support for hexbin plots

I try to convert a matplotib hexbin plot, but it does not work.

NotImplementedError: offset before transform

Imshow and matshow

Hi,

This is a very useful package and making maps that include basic geometries seems to work like a charm. I was wondering if the module could be extended to plot other type of information. E.g. it would be great if one could use the plt.imshow and plt.matshow commands in order to plot GIS raster files on a map.

Popup text for exported features

Hi!

Is there any way to annotate matplotlib points/line segments in such a way that they become marker popups in leaflet? To clarify, I'd like reproduce the following effect:

import os
import folium
mapit = folium.Map()
PER = (-31.940, 115.967)
MEL = (-37.673, 144.843)
folium.CircleMarker(location=MEL, color='#ff0000',
                        fill_color='#ff0000', popup='Melbourne airport',
                        radius=4).add_to(mapit)
folium.CircleMarker(location=PER, color='#ff0000',
                        fill_color='#ff0000', popup='Perth airport',
                        radius=4).add_to(mapit)
folium.PolyLine([PER, MEL], color='#ffff00', popup='MEL-PER').add_to(mapit)
mapit.save(os.path.expanduser('~/Desktop/perth.html'))

Maybe this is impossible but I thought I'd ask. =) Thanks!

Mplleaflet not showing plot .

Hi,
I have tripcolor trianulation plot wave plot and that plot i need to overlap with background as google map with zoom function , so i tried mplleaflet but the tripcolor plot is not coming over the map.
can you tell me how to do this.

%matplotlib inline
import matplotlib.pyplot as plt
from scipy.io import loadmat
import mplleaflet
import datetime
import pandas as pd
from dateutil.parser import parse

import matplotlib as mpl

from pylab import *

import numpy as np
import os

#fig=plt.figure()
#fig, ax = plt.subplots(figsize=(13, 13), subplot_kw=dict(projection=projection))

os.environ['PROJ_LIB'] = r'C:\Users\walps\Anaconda3\pkgs\proj4-5.2.0-ha925a31_1\Library\share'

from datetime import timedelta

import matplotlib.tri as mtri
datamat = loadmat('IOEC_ECM2017_BC.mat')
Xp = datamat['Xp']
Yp = datamat['Yp']
strt = datetime.datetime(2017, 1, 11, 0, 0)
end = datetime.datetime(2017, 1, 21, 0, 0)
numdays = 3

def perdelta(strt, end, delta):
curr = strt
while curr < end:
yield curr
curr += delta

Read element file

data = pd.read_table('fort.ele',delim_whitespace=True,names=('A','B','C','D'))

tri_new = pd.read_csv('fort.ele', delim_whitespace=True, names=('A', 'B', 'C', 'D'), usecols=[1, 2, 3], skiprows=1,
dtype={'D': np.int})

data1=data[['B','C','D']]

tri=data1[1:]

dateList = []
for result in perdelta(strt, strt + timedelta(days=2), timedelta(hours=3)):
dat = result
# print(result)
dt = parse(str(dat))
yr = dt.year
mn = dt.month
d = dt.day
hr = dt.hour
mi = dt.minute
# print(y,mn,d,hr,mi)
if hr < 10:
# d='0'+str(d)
hr = '0' + str(hr)
else:
d = str(d)
hr = str(hr)
if int(d) < 10:
d = '0' + str(d)
else:
d = str(d)
varname = 'Hsig_' + str(yr) + '0' + str(mn) + str(d) + '_' + hr + '0000'
print(varname)

x = Xp.flatten()
y = Yp.flatten()
z = datamat[varname]
z1 = z.flatten()

tri_sub = tri_new.apply(lambda x: x - 1)
triang = mtri.Triangulation(x, y, triangles=tri_sub)

#pp = plt.tripcolor(triang, z1, cmap='jet', vmin=0.0, vmax="0.5")
#pp = plt.tripcolor(triang, z1,cmap='jet')
# ax.tripcolor()
#     #
#     # plt.suptitle('Significant Wave Height', fontname='Comic Sans MS', fontweight='bold', fontsize=12, color="red")
#     # plt.title("Experimental forecast for " + str(hr) + ':' + '0' + str(mi) + ' ' + str(d) + '-' + 'Jan' + '-' + str(yr),
#     #           fontsize=10, fontname='sans-serif', color="green")
#     #
#     # plt.savefig(varname + '.png', dpi=500)

# plt.colorbar()
#plt.show()
#mplleaflet.show()
fig, ax = plt.subplots()
tp=ax.tripcolor(triang, z1, vmin=0, vmax=2)
#mplleaflet.display(fig=tp)
mplleaflet.display()
mplleaflet.show()
break

display() doesn't work - 'base64' is not a text encoding

Hi. I've recently downloaded the package and have been messing around with some basic examples.

The following snippet runs without error,

%matplotlib inline

import mplleaflet
import matplotlib.pyplot as plt

plt.plot([0,45], [0,45])

mplleaflet.show()

but changing mplleaflet.show() to mplleaflet.display() returns the following error

---------------------------------------------------------------------------
LookupError                               Traceback (most recent call last)
<ipython-input-6-a8022d0ab3fb> in <module>()
      6 plt.plot([0,45], [0,45])
      7 
----> 8 mplleaflet.display()

C:\Program Files\Miniconda3\lib\site-packages\mplleaflet\_display.py in display(fig, closefig, **kwargs)
    153     # We embed everything in an iframe.
    154     iframe_html = '<iframe src="data:text/html;base64,{html}" width="{width}" height="{height}"></iframe>'\
--> 155     .format(html = html.encode('base64'),
    156             width = '100%',
    157             height= int(60.*fig.get_figheight()),

LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

I'm running Python 3.4.3, iPython 4.0.0 through Jupyter 4.0.6, matplotlib 1.4.3 and mplleaflet 0.0.4. OS is Win8.1 (64bit).

Cheers,
Eilam

_gridOnMajor bug with recent versions of Matplotlib

After upgrading to Matplotlib 3.3.3, the following error appears when trying to use mplleaflet:

'XAxis' object has no attribute '_gridOnMajor

The problem comes from mplexporter and was corrected in mpld3's mplexporter (see mpld3/mpld3#479) but the correction has not been propagated to the version of mplexporter used by mplleaflet.

Can't import mplleaflet on python2.7

import mplleaflet


ImportError Traceback (most recent call last)
in ()
----> 1 import mplleaflet

/Users/me/anaconda/lib/python2.7/site-packages/mplleaflet/init.py in ()
----> 1 import templates
2 from _display import show, display, save_html, fig_to_html, fig_to_geojson

ImportError: No module named templates

Can't import, Python 3

I'm unable to import mplleaflet into my Python 3 Jupyter notebook. Here's the code and error:

`
In [159]:

import mplleaflet
mplleaflet.show()

ModuleNotFoundError Traceback (most recent call last)
in ()
----> 1 import mplleaflet
2 mplleaflet.show()

ModuleNotFoundError: No module named 'mplleaflet'`

I already have my data mapped out, but I wanted to create an interactive map, mostly to see the locations and get a better understanding of the data that way.

Support save fig as image

Do you have any suggestion how easily an image could be extracted of the html, that the user can save as png or alike?

plt.scatterplot c argument doesn't work

When I run this example, I get the following traceback:

import mplleaflet
import matplotlib.pyplot as plt

plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
mplleaflet.display()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-100-b851626ef3d4> in <module>()
      1 plt.scatter([0, 10, 0, 10], [0, 0, 10, 10], c=[1, 2, 3, 4])
----> 2 mplleaflet.display()

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplleaflet/_display.pyc in display(fig, closefig, **kwargs)
    136         plt.close(fig)
    137 
--> 138     html = fig_to_html(fig, template="ipynb.html", **kwargs)
    139     return HTML(html)
    140 

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplleaflet/_display.pyc in fig_to_html(fig, template, tiles, crs, epsg)
     70     renderer = LeafletRenderer(crs=crs, epsg=epsg)
     71     exporter = Exporter(renderer)
---> 72     exporter.run(fig)
     73 
     74     attribution = _attribution + ' | ' + tiles[1]

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplexporter/exporter.pyc in run(self, fig)
     49             import matplotlib.pyplot as plt
     50             plt.close(fig)
---> 51         self.crawl_fig(fig)
     52 
     53     @staticmethod

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplexporter/exporter.pyc in crawl_fig(self, fig)
    116                                        props=utils.get_figure_properties(fig)):
    117             for ax in fig.axes:
--> 118                 self.crawl_ax(ax)
    119 
    120     def crawl_ax(self, ax):

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplexporter/exporter.pyc in crawl_ax(self, ax)
    138                 self.draw_patch(ax, patch)
    139             for collection in ax.collections:
--> 140                 self.draw_collection(ax, collection)
    141             for image in ax.images:
    142                 self.draw_image(ax, image)

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplexporter/exporter.pyc in draw_collection(self, ax, collection, force_pathtrans, force_offsettrans)
    270                                            offset_order=offset_order,
    271                                            styles=styles,
--> 272                                            mplobj=collection)
    273 
    274     def draw_image(self, ax, image):

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplexporter/renderers/base.pyc in draw_path_collection(self, paths, path_coordinates, path_transforms, offsets, offset_coordinates, offset_order, styles, mplobj)
    253 
    254         for tup in self._iter_path_collection(paths, path_transforms,
--> 255                                               offsets, styles):
    256             (path, path_transform, offset, ec, lw, fc) = tup
    257             vertices, pathcodes = path

/Users/shoyer/miniconda/envs/rapid/lib/python2.7/site-packages/mplexporter/renderers/base.pyc in _iter_path_collection(paths, path_transforms, offsets, styles)
    190         N = max(len(paths), len(offsets))
    191 
--> 192         if not path_transforms:
    193             path_transforms = [np.eye(3)]
    194 

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Thanks for your work on this project! I can't believe I just discovered it yesterday :).

Maps won't display inline on latest Jupyter/IPython

Hi, I'm running master of IPython/Jupyter (e013d522d028f98e73f08f057b27cf06d055d43a) and I'm not able to get the widgets to display properly. Running the simple example of:

%matplotlib inline
import mplleaflet
mplleaflet.display(tiles="mapbox bright")

the box displays, it has the zoom buttons and the leaflet attribution, but it's blank. In the javascript console, the error is Uncaught TypeError: Cannot read property 'lat' of undefined. I'm wondering if this could be related to changes in how javascript has to be loaded in the current version of IPython? Any suggestions?

Drag matplotlib patches with mouse on maps

Hello,

I know how to drag matplotlib patches like rectangles and polygons with mouse as in the examples on this page event_handling.

I would love to be able to do it with mplleaflet, that is to say with openstreetmaps background.

However, I wonder if it is possible given that mplleaflet displays in web browser whereas matplotlib relies on another backend (tk by default I think) to collect events.

If it is currently not possible, do you think there are any chance it could become possible ? or perhaps another library enables it

Regards

conflict with python 3.6

Hi,

I tried to install mplleaflet with conda

conda install -c ioos mplleaflet=0.0.5

I received the following message

Fetching package metadata .............
Solving package specifications: .


UnsatisfiableError: The following specifications were found to be in conflict:
  - mplleaflet 0.0.5* -> python 3.4*
  - python 3.6*
Use "conda info <package>" to see the dependencies for each package.

It seems that I have python 3.6, but mplleaflet does not work with python 3.6.
Could you please help me by fixing this issue?
If this is not because the conflict with python 3.6, could you please also suggest how to fix this?
Thank you.

Add the plot legend to the GeoJSON properties

I guess that mplleaflet follow the simplestyle-spec closely and what I propose here this is not in the simplestyle-spec, but it would be nice to use the legend information to create popups later on. (Or just to keep track of who-is-who in the JSON.)

@jwass is that something you would be OK to add? If so I can take try to implementing this.

Allow plt.display() usage as plt.show()

Hey!

Following the simplest example to plot a point, I can do

import matplotlib.pyplot as plt
import mplleaflet

plt.hold(True)
plt.plot(-46.6462204, -23.580856, 'ro')
mplleaflet.show()

, which opens a new tab with the map. Instead, I would like to show the map inline using .display(). So I tried

import matplotlib.pyplot as plt
import mplleaflet

plt.hold(True)
plt.plot(-46.6462204, -23.580856, 'ro')
mplleaflet.display()

but it gives the error

---------------------------------------------------------------------------
PyDeadObjectError                         Traceback (most recent call last)
<ipython-input-20-ae4252cc7a12> in <module>()
      5 plt.plot(-46.6462204, -23.580856, 'ro')
      6 # plt.show()
----> 7 mplleaflet.display()

/home/paulo/.virtualenvs/geoviewer/local/lib/python2.7/site-packages/mplleaflet/_display.pyc in display(fig, closefig, **kwargs)
    136         plt.close(fig)
    137 
--> 138     html = fig_to_html(fig, template="ipynb.html", **kwargs)
    139     return HTML(html)
    140 

/home/paulo/.virtualenvs/geoviewer/local/lib/python2.7/site-packages/mplleaflet/_display.pyc in fig_to_html(fig, template, tiles, crs, epsg)
     70     renderer = LeafletRenderer(crs=crs, epsg=epsg)
     71     exporter = Exporter(renderer)
---> 72     exporter.run(fig)
     73 
     74     attribution = _attribution + ' | ' + tiles[1]

/home/paulo/.virtualenvs/geoviewer/local/lib/python2.7/site-packages/mplexporter/exporter.pyc in run(self, fig)
     45         if fig.canvas is None:
     46             canvas = FigureCanvasAgg(fig)
---> 47         fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi)
     48         if self.close_mpl:
     49             import matplotlib.pyplot as plt

/home/paulo/.virtualenvs/geoviewer/local/lib/python2.7/site-packages/matplotlib/figure.pyc in savefig(self, *args, **kwargs)
   1468             self.set_frameon(frameon)
   1469 
-> 1470         self.canvas.print_figure(*args, **kwargs)
   1471 
   1472         if frameon:

/home/paulo/.virtualenvs/geoviewer/local/lib/python2.7/site-packages/wx-2.8-gtk2-unicode/wx/_core.pyc in __getattr__(self, *args)
  14613         if not hasattr(self, "_name"):
  14614             self._name = "[unknown]"
> 14615         raise PyDeadObjectError(self.attrStr % self._name)
  14616 
  14617     def __nonzero__(self):

PyDeadObjectError: The C++ part of the FigureCanvasWxAgg object has been deleted, attribute access no longer allowed.

As one can see, I have a virtualenv where I'm running this code, where I also have a Django project with django-extensions enabled. The current pip freeze -l is:

$ pip freeze -l
arrow==0.4.4
backports.ssl-match-hostname==3.4.0.2
certifi==14.5.14
colorclass==1.1.2
Django==1.7.2
django-appconf==0.6
django-bitfield==1.7.1
django-extensions==1.4.9
django-geoposition==0.2.2
django-getenv==1.3.1
django-shell-plus==1.1.5
docutils==0.12
foursquare==20130707
geojson==1.0.9
geopy==1.7.1
httplib2==0.9
ipdb==0.8
ipython==2.3.1
Jinja2==2.7.3
lockfile==0.10.2
lunch==1.0.1
MarkupSafe==0.23
matplotlib==1.4.2
mock==1.0.1
mplexporter==0.0.1
mplleaflet==0.0.1
MySQL-python==1.2.5
nose==1.3.4
numpy==1.9.1
numpydoc==0.5
poster==0.8.1
Pygments==2.0.2
pyparsing==2.0.3
pysolr==3.2.0
python-dateutil==2.4.0
python-geohash==0.8.5
pytz==2014.10
pyzmq==14.5.0
requests==2.5.1
simplejson==3.6.5
six==1.9.0
Sphinx==1.2.3
tornado==4.1

So, because I don't know if it's a mplleaflet's bug or feature, or if I'm missing some dependency in my machine, I would like some help.

Thanks!

Manage CRS from new geopandas release

Hi all! With new gepandas release, the pyproj.CRS object has been enriched and the old way (pyproj4) to specify projection as parameter (`crs') seems to have changed considerably.

When you try to plot a gd over a a layer with display method:

# 1. Plot data:
ax = gdf.plot()

# 2. Display dinamic map
mplleaflet.display(fig=ax.figure, crs=ax.crs)

The following error is returned:

TypeError: type object argument after ** must be a mapping, not CRS

This is seems to be explained because CRS with new geopandas release has a new obtect type.

Passing the crs with the .to_dict() this error doesn't appears again, but as I'm still getting some warnings like this one:

UserWarning: You will likely lose important projection information when converting to a PROJ string from another format. See: https://proj.org/faq.html#what-is-the-best-format-for-describing-coordinate-reference-systems
  proj_string = self.to_proj4()

I would like to know if this is the correct way to pass the gdf.crs as parameter in the display method.

Great work wit this library, much thanks!

error : linux Fedora 29 with functools_lru_cache

error with
I uninstall and install it , but I got same error:

[mythcat@desk ~]$ python
Python 2.7.15 (default, Oct 15 2018, 15:26:09) 
[GCC 8.2.1 20180801 (Red Hat 8.2.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mplleaflet
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mythcat/.local/lib/python2.7/site-packages/mplleaflet/__init__.py", line 3, in <module>
    from mplleaflet._display import (
  File "/home/mythcat/.local/lib/python2.7/site-packages/mplleaflet/_display.py", line 10, in <module>
    import matplotlib.pyplot as plt
  File "/home/mythcat/.local/lib/python2.7/site-packages/matplotlib/__init__.py", line 130, in <module>
    from matplotlib.rcsetup import defaultParams, validate_backend, cycler
  File "/home/mythcat/.local/lib/python2.7/site-packages/matplotlib/rcsetup.py", line 29, in <module>
    from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
  File "/home/mythcat/.local/lib/python2.7/site-packages/matplotlib/fontconfig_pattern.py", line 28, in <module>
    from backports.functools_lru_cache import lru_cache
ImportError: No module named functools_lru_cache
>>> 
[4]+  Stopped                 python
[mythcat@desk ~]$ pip install backports.functools_lru_cache --user
Requirement already satisfied: backports.functools_lru_cache in ./.local/lib/python2.7/site-packages (1.5)

contourf example doesn't work on my machine

I can't seem to get any contourf plots to work with mplleaflet. Other plot types (e.g., scatter plots) work fine.

The example runs without any errors on my machine, but it generates a map with only the background layer.

Any ideas for how to debug this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.