Créer une image sans les axes et les étiquettes avec matplotlib

Dans cet article on va voir comment créer une image avec matplotlib sans les contours ou les labels.

Suppression du cadre et des étiquettes d'une figure matplotlib

Regardons cet exemple d'utilisation de matplotlib

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt

def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0):
    Xmu = X-mux
    Ymu = Y-muy
    rho = sigmaxy/(sigmax*sigmay)
    z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay)
    denom = 2*np.pi*sigmax*sigmay*np.sqrt(1-rho**2)
    return np.exp(-z/(2*(1-rho**2))) / denom

delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2-Z1  # difference of Gaussians

my_dpi=100

Shape = Z.shape

fig = plt.figure(figsize=(Shape[1]/my_dpi, Shape[0]/my_dpi), dpi=my_dpi)

im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
                origin='lower', extent=[-3,3,-3,3],
                vmax=abs(Z).max(), vmin=-abs(Z).max())

fig.savefig('MatplotlibImageNoFrame01.png', dpi=my_dpi)
plt.show()

Créer une image sans les axes et les étiquettes avec matplotlib (image de départ)
Créer une image sans les axes et les étiquettes avec matplotlib (image de départ)

Pour supprimer le cadre ou le contour d'une image, il suffit d'utiliser la commande set_axis_off(). Par exemple, vous pouvez ajouter cette commande après avoir défini l'objet Axes avec la commande ax = plt.Axes(fig, [0., 0., 1., 1.]), suivi de l'ajout de cet objet à la figure avec la commande fig.add_axes(ax). Exemple:

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt

def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0):
    Xmu = X-mux
    Ymu = Y-muy
    rho = sigmaxy/(sigmax*sigmay)
    z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay)
    denom = 2*np.pi*sigmax*sigmay*np.sqrt(1-rho**2)
    return np.exp(-z/(2*(1-rho**2))) / denom

delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2-Z1  # difference of Gaussians

my_dpi=100

Shape = Z.shape

fig = plt.figure(figsize=(Shape[1]/my_dpi, Shape[0]/my_dpi), dpi=my_dpi)

ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)

im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
                origin='lower', extent=[-3,3,-3,3],
                vmax=abs(Z).max(), vmin=-abs(Z).max())

fig.savefig('MatplotlibImageNoFrame02.png', dpi=my_dpi)

plt.savefig("test.png", bbox_inches='tight', dpi=200, facecolor='red', pad_inches = 0)

plt.show()

Créer une image sans les axes et les étiquettes avec matplotlib (résultat)
Créer une image sans les axes et les étiquettes avec matplotlib (résultat)

Comment sauvegarder la figure matplotlib ?

Pour sauvegarder la figure matplotlib que vous avez créée, vous pouvez enregistrer celle-ci sous forme de fichier image pour l'utiliser dans d'autres applications. Pour une sauvegarde optimale, n'oubliez pas d'inclure les paramètres "bbox_inches='tight'" et "pad_inches=0" dans la méthode save().

plt.savefig("MatplotlibImageNoFrame02.png", bbox_inches='tight', dpi=200, facecolor='red', pad_inches = 0)

Exemple d'utilisation :

Utilisez Folium pour créer une carte interactive, puis utilisez Cartopy pour générer une image à superposer sur la carte. Commencez par créer une carte Mercator avec Cartopy, étape 1.

import cartopy.crs as ccrs
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib as mpl

plt.figure(figsize=(16,9))

ax = plt.axes(projection=ccrs.Mercator(min_latitude=-85.0, max_latitude=85.0, globe=None, latitude_true_scale=1))

ax.set_axis_off()

ax.coastlines(resolution='110m')

plt.savefig("cartopy_mercator.png", bbox_inches='tight', dpi=200, pad_inches = 0)

plt.show()

How to create and save a matplotlib figure that doesn't show frame and labels ?
How to create and save a matplotlib figure that doesn't show frame and labels ?

Étape 2 : superposer l'image

import os
import folium

from folium.raster_layers import ImageOverlay

m = folium.Map([0,0], zoom_start=1, crs='EPSG3857')
merc = "cartopy_mercator.png"

folium.TileLayer(
        tiles = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
        attr = 'Esri',
        name = 'Esri Satellite',
        overlay = False,
        control = True
       ).add_to(m)

if not os.path.isfile(merc):
    print(f"Could not find {merc}")
else:
    img = folium.raster_layers.ImageOverlay(
        name="Mercator projection SW",
        image=merc,
        bounds=[[[-85,-180]],[85,180]],
        opacity=0.5,
        interactive=True,
        cross_origin=False,
        zindex=1,
    )

    folium.Popup("I am an image").add_to(img)

    img.add_to(m)
    folium.LayerControl().add_to(m)

m

How to create and save a matplotlib figure that doesn't show frame and labels ?
How to create and save a matplotlib figure that doesn't show frame and labels ?

Références

Liens Site
set_axis_off matplotlib.org
add_axes() matplotlib.org
Image

of