Comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python ?

Published: 04 mars 2021

Tags: Python; Matplotlib; Numpy;

DMCA.com Protection Status

Exemples de comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python:

Tracer un diagramme en bâtons avec une barre de couleurs (Exemple 1)

Exemple de comment tracer un diagramme en bâtons avec une barre de couleurs

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

data_x = [0,1,2,3]
data_hight = [60,60,80,100]
data_color = [200.,600.,0.,750.]

data_color_normalized = [x / max(data_color) for x in data_color]

fig, ax = plt.subplots(figsize=(15, 4))

my_cmap = plt.cm.get_cmap('GnBu')
colors = my_cmap(data_color_normalized)

rects = ax.bar(data_x, data_hight, color=colors)

sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))

sm.set_array([])

cbar = plt.colorbar(sm)
cbar.set_label('Color', rotation=270,labelpad=25)

plt.xticks(data_x)    
plt.ylabel("Y")

plt.title('How to plot a bar chart with a colorbar with matplotlib ?')

plt.savefig("bar_chart_with_colorbar_01.png", bbox_inches='tight')

plt.show()

Comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python ?
Comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python ?

Tracer un diagramme en bâtonsL couleur normalisée (Exemple 2)

Pour normaliser la couleur entre 0 et 1, remplacez simplement

sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))

par

sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color_normalized)))

Comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python ?
Comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python ?

Tracer un diagramme en bâtons: couleur associée à la hauteur de la barre (Exemple 3)

Un autre exemple: utiliser une barre de couleurs pour afficher la hauteur de la barre

import matplotlib.pyplot as plt
from matplotlib.cm import ScalarMappable

data_x = [0,1,2,3]
data_hight = [60,60,80,100]

data_hight_normalized = [x / max(data_hight) for x in data_hight]

fig, ax = plt.subplots(figsize=(15, 4))

my_cmap = plt.cm.get_cmap('GnBu')
colors = my_cmap(data_hight_normalized)

rects = ax.bar(data_x, data_hight, color=colors)

sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_hight)))

sm.set_array([])

cbar = plt.colorbar(sm)
cbar.set_label('Color', rotation=270,labelpad=25)

plt.xticks(data_x)    
plt.ylabel("Y")

plt.title('How to plot a bar chart with a colorbar with matplotlib ?')

plt.savefig("bar_chart_with_colorbar_03.png", bbox_inches='tight')

plt.show()

Comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python ?
Comment tracer un diagramme en bâtons avec une barre de couleurs avec matplotlib en python ?

Références

Image

of