D. Lef
D. Lef

Reputation: 259

Extract color data from Matplotlib.pcolormesh() plot for conversion to .kml or other format

I have a program that plots data on various map software, such as Google Earth and Leaflet.

I need to represent a certain data set, which is stored as a numpy array, on Google Earth, using square polygons as the data format within the corresponding kml file.

Pcolormesh produces a grid of color squares. Further, it allows you to extract the coordinates of the vertices of each square. If I then feed these into the simplekml library's polygon maker, it works great, only I cannot figure out how to extract the color data from matplotlib and pass it to the object I am creating. I have been trying to figure it out from the documentation.

Here is what I have so far. The example uses Cartopy, but I believe it is only matplotlib that is causing my problem.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.examples.waves import sample_data
import pdb
import simplekml

ax = plt.axes(projection=ccrs.Robinson())

ax.set_global()

lons, lats, data = sample_data(shape=(20, 40))

default_cmap = 'RdBu_r'

def make_path_polygons(mesh):
    kml = simplekml.Kml()
    paths = mesh.get_paths()
    for path in paths:
        kml.newpolygon(name="newpoly", outerboundaryis=path.vertices)
        #NEED TO SET COLOR HERE
    kml.save("gridpaths.kml")

mesh = plt.pcolormesh(lons, lats, data, transform=ccrs.PlateCarree(), cmap=default_cmap)
print(mesh.get_facecolors()) #Result: array([[0.1215, 0.4667, 0.7058]]), I would have hoped this returned a sequence corresponding to the coordinate data, but seems it does not
make_path_polygons(mesh)

ax.coastlines()
ax.gridlines()

plt.savefig("pcm.png")

Here is my matplotlib plot: This is what my mpl plot looks like if I save the figure

And here is the .kml in Google Earth: And this is how it appears in Google Earth

I understand why the GE result is colorless, because right now I am only passing coordinate data to simplekml and nothing else. But how do I get that data out of the mpl.QuadMesh object? Any help would be greatly appreciated, thank you.

Upvotes: 1

Views: 2026

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339280

The full color information should be available via the array of the QuadMesh together with the colormap and norm in use.

mesh = plt.pcolormesh(...)

colors = mesh.cmap(mesh.norm(mesh.get_array()))

Upvotes: 2

Related Questions