1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# Données
x = np.linspace(0, 10, 500)
y = x**2
# Création de segments
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
# Colormap. Attention, il y n points (n valeurs de y), mais n-1 segments
# Je suppose ici, pour l'exercice que c'est la valeur moyenne entre les deux
# points du segment qui défini la couleur
colors = list()
for y1, y2 in zip(y[:-1], y[1:]):
val = 0.5 * (y1 + y2)
if val <= 10:
colors.append('g')
elif val < 50:
colors.append('y')
else:
colors.append('r')
lc = LineCollection(segments, colors=colors)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale() # sans cela, ou autre set_xlim(), la figure s'affiche sur 0-1
plt.show() |
Partager