Dan*_*iel 9 python plot matplotlib
我想用matplotlib绘制一个2d数据集,使每个数据点的标记颜色不同.我在五彩线上找到了这个例子(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)
Run Code Online (Sandbox Code Playgroud)
结果情节看起来应该如此,但绘图变得非常慢,我需要它很快.加速绘图是否有一个聪明的伎俩?
Gre*_*reg 18
我相信你可以通过以下方式达到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)
Run Code Online (Sandbox Code Playgroud)
Scatter接受c作为浮点序列,它将使用cmap映射到颜色.

使用timeit时间减少10倍(原始方法约为1.25秒,此处为76.8毫秒)
| 归档时间: |
|
| 查看次数: |
8999 次 |
| 最近记录: |