How to get differents colors in a single line in a

2020-07-18 10:00发布

问题:

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.

回答1:

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