【问题标题】:cmap for use with line plot用于线图的 cmap
【发布时间】:2015-08-16 19:31:58
【问题描述】:

我有一个颜色值列表(如果有帮助,可以采用以下两种格式:十六进制 ('#ffffff') 或 rgb (255,255,255))。这些颜色与点之间的线段明确对应。目前我通过以下方式绘制一条线作为线段的集合:

import matplotlib.pyplot as plt
import itertools
colors = itertools.cycle('#ffffff', '#ffffff', '#ff0320', '#452143', ...)
t = (0, 1, 2, 3, ...)
var1 = (43, 15, 25, 9, ...)
ax = plt.subplot2grid((3,1), (0,0), colspan=3, rowspan=1)

ps = [(t,var1) for (t,var1) in zip(t, val)]
for start, end in zip(ps[:-1], ps[1:]):
    t, var1 = zip(start, end)
    c = next(colors)    
    ax.plot(t, var1, color=c)

但是,由于我为每个点设置了颜色,我更愿意为绘图设置一个 cmap。如何将颜色列表转换为绘制线条时可以使用的 cmap?

【问题讨论】:

  • 您的代码中的foo 是什么?
  • foo 应该是要绘制的轴。已编辑。
  • 为什么不只是plt.scatter((0, 1, 2, 3), (43, 15, 25, 9), c=('#ffffff', '#ffffff', '#ff0320', '#452143'))
  • 一些点之间的距离很远,所以分散是不合适的,因为我想显示一条插值该距离的线。

标签: python numpy matplotlib plot


【解决方案1】:

正如 tcaswell 所说,为此使用 LineCollection

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection

# a random walk
xy = np.cumsum(np.random.randn(1000, 2), axis=0)
z = np.linspace(0, 1, 1000)

lc = LineCollection(zip(xy[:-1], xy[1:]), array=z, cmap=plt.cm.hsv)

fig,  ax = plt.subplots(1, 1)
ax.add_collection(lc)
ax.margins(0.1)
plt.show()

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多