【问题标题】:python matplotlib with a line color gradient and colorbar带有线条颜色渐变和颜色条的 python matplotlib
【发布时间】:2016-03-18 01:11:40
【问题描述】:

我一直在玩弄这个问题,并且接近我想要的,但缺少那一两行。

基本上,我想绘制一条线,其颜色会根据第三个数组的值发生变化。潜伏着我发现这很好用(尽管速度很慢)并且代表了问题

import numpy as np
import matplotlib.pyplot as plt
c = np.arange(1,100)
x = np.arange(1,100)
y = np.arange(1,100)

cm = plt.get_cmap('hsv')

fig = plt.figure(figsize=(5,5))
ax1 = plt.subplot(111)

no_points = len(c)
ax1.set_color_cycle([cm(1.*i/(no_points-1)) 
                     for i in range(no_points-1)])

for i in range(no_points-1):
    bar = ax1.plot(x[i:i+2],y[i:i+2])
plt.show()

这给了我这个:

我希望能够在这个情节中包含一个颜色条。到目前为止,我还无法破解它。可能会有其他行包含不同的 x,y 但相同的 c,所以我认为 Normalize 对象将是正确的路径。

更大的图景是该图是 2x2 子图网格的一部分。我已经使用 matplotlib.colorbar.make_axes(ax4) 为颜色条轴对象腾出空间,其中 ax4 带有第 4 个子图。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

看看Matplotlib gallery和dpsanders' colorline notebook中的multicolored_line example:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as mcoll

def multicolored_lines():
    """
    http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
    http://matplotlib.org/examples/pylab_examples/multicolored_line.html
    """

    x = np.linspace(0, 4. * np.pi, 100)
    y = np.sin(x)
    fig, ax = plt.subplots()
    lc = colorline(x, y, cmap='hsv')
    plt.colorbar(lc)
    plt.xlim(x.min(), x.max())
    plt.ylim(-1.0, 1.0)
    plt.show()

def colorline(
        x, y, z=None, cmap='copper', norm=plt.Normalize(0.0, 1.0),
        linewidth=3, alpha=1.0):
    """
    http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
    http://matplotlib.org/examples/pylab_examples/multicolored_line.html
    Plot a colored line with coordinates x and y
    Optionally specify colors in the array z
    Optionally specify a colormap, a norm function and a line width
    """

    # Default colors equally spaced on [0,1]:
    if z is None:
        z = np.linspace(0.0, 1.0, len(x))

    # Special case if a single number:
    # to check for numerical input -- this is a hack
    if not hasattr(z, "__iter__"):
        z = np.array([z])

    z = np.asarray(z)

    segments = make_segments(x, y)
    lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm,
                              linewidth=linewidth, alpha=alpha)

    ax = plt.gca()
    ax.add_collection(lc)

    return lc

def make_segments(x, y):
    """
    Create list of line segments from x and y coordinates, in the correct format
    for LineCollection: an array of the form numlines x (points per line) x 2 (x
    and y) array
    """

    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    return segments

multicolored_lines()


请注意,调用plt.plot 数百次往往会降低性能。 使用LineCollection 构建多色线段要快得多。

【讨论】:

  • 我也想粘贴一个答案,但我会投票赞成:-p
  • 太棒了!谢谢你,正是我想要的!
  • unutbu 一如既往的出色回答。有人会认为使用一些默认的 matplotlib 参数应该更容易做到这一点。
  • 迟来的反应,你怎么能在这里添加另一行? (一张图中的两条线,每条线有不同的颜色)
猜你喜欢
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 2021-01-07
  • 2020-10-07
  • 2021-06-03
相关资源
最近更新 更多