Reputation: 3559
I am using matplotlib to create the plots. I have to draw a line in a chart which color must be defined in function of each point. For example, I need a line where the points under 2000 are painted red, and points above 2000 are painted blue. How can I get this ? Do you know a similar solution or workaround to achieve it?
This is my sample code, which paint the hole line blue (default color I guess)
def draw_curve(points, labels):
plt.figure(figsize=(12, 4), dpi=200)
plt.plot(labels,points)
filename = "filename.png"
plt.savefig("tmp/{0}".format(filename))
figure = plt.figure()
plt.close(figure)
So, in the image below, I would like that values above the light blue horizontal line were painted in a different color than under values.
Thanks in advance.
Upvotes: 4
Views: 5118
Reputation: 36635
You have to color every segment of your line:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
# my func
x = np.linspace(0, 2 * np.pi, 100)
y = 3000 * np.sin(x)
# select how to color
cmap = ListedColormap(['r','b'])
norm = BoundaryNorm([2000,], cmap.N)
# get segments
xy = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.hstack([xy[:-1], xy[1:]])
# make line collection
lc = LineCollection(segments, cmap = cmap, norm = norm)
lc.set_array(y)
# plot
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
plt.show()
More examples here: http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Upvotes: 3