【问题标题】:matplotlib - change marker color along plot linematplotlib - 沿绘图线更改标记颜色
【发布时间】:2013-09-08 06:57:40
【问题描述】:

我想用 matplotlib 绘制一个二维数据集,以便每个数据点的标记颜色不同。我在五彩线(http://matplotlib.org/examples/pylab_examples/multicolored_line.html)上找到了这个例子。但是,在绘制带有标记的线时,这似乎不起作用。

我提出的解决方案分别绘制了每个点:

import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np

# The data
x = np.linspace(0, 10, 1000)
y = np.sin(2 * np.pi * x)

# The colormap
cmap = cm.jet

# Create figure and axes
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(1, 1, 1)

# Plot every single point with different color
for i in range(len(x)):
    c = cmap(int(np.rint(x[i] / x.max() * 255)))
    ax.plot(x[i], y[i], 'o', mfc=c, mec=c)
    ax.set_xlim([x[0], x[-1]])
    ax.set_ylim([-1.1, 1.1])
    ax.set_xlabel('x')
    ax.set_ylabel('y')

plt.draw()
plt.show()

# Save the figure
fig.savefig('changing_marker_color.png', dpi=80)

生成的绘图看起来应该是这样,但绘图变得非常慢,我需要它很快。有没有加快绘图速度的巧妙技巧?

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    我相信您可以通过ax.scatter 实现这一目标:

    # The data
    x = np.linspace(0, 10, 1000)
    y = np.sin(2 * np.pi * x)
    
    # The colormap
    cmap = cm.jet
    
    # Create figure and axes
    fig = plt.figure(1)
    fig.clf()
    ax = fig.add_subplot(1, 1, 1)
    
    c = np.linspace(0, 10, 1000)
    ax.scatter(x, y, c=c, cmap=cmap)
    

    Scatter 接受 c 作为浮点序列,将使用 cmap 映射到颜色。

    使用timeit,我的时间减少了 10 倍(原始方法约为 1.25 秒,此处为 76.8 毫秒)

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2018-07-08
      • 1970-01-01
      • 2012-08-26
      • 2016-02-14
      • 2020-06-16
      • 2012-02-15
      • 2014-10-04
      • 1970-01-01
      相关资源
      最近更新 更多