本文介绍了如何在 Matplotlib 图中的单行中获取不同的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib创建图.我必须在图表中画一条线,必须根据每个点的功能定义颜色.例如,我需要一条线,其中2000年以下的点涂成红色,而2000年以上的点涂成蓝色.我怎么能得到这个?您知道类似的解决方案或解决方法吗?

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.

谢谢.

推荐答案

你必须为线条的每一段着色:

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()

更多示例:http://matplotlib.org/examples/pylab_examples/multicolored_line.html

这篇关于如何在 Matplotlib 图中的单行中获取不同的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 15:49