【问题标题】:How to get differents colors in a single line in a Matplotlib figure?如何在 Matplotlib 图中的一行中获得不同的颜色?
【发布时间】:2016-10-29 08:20:10
【问题描述】:

我正在使用 matplotlib 创建绘图。我必须在图表中画一条线,必须在每个点的函数中定义颜色。例如,我需要一条线,将 2000 以下的点涂成红色,将 2000 以上的点涂成蓝色。我怎样才能得到这个?你知道实现它的类似解决方案或解决方法吗?

这是我的示例代码,将孔线涂成蓝色(我猜是默认颜色)

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)

因此,在下图中,我希望将浅蓝色水平线上方的值绘制成与下方值不同的颜色。

提前致谢。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

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

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 文档中看到这部分。
猜你喜欢
  • 2012-11-03
  • 2014-04-03
  • 2021-10-22
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多