1

我的代码可以很好地生成和绘制随机游走。但是,我想根据跳跃的大小为每条线着色。这是我的代码:

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

def randomwalk(N):
    x, y, bigness = np.zeros((N)), np.zeros((N)), np.zeros((N))
    for n in range(0,N):
        angle = random.random() * 2*np.pi
        jump = np.random.normal(0, 50)

        x[n] = x[n-1] + (np.cos(angle) * jump)
        y[n] = y[n-1] + (np.sin(angle) * jump)
        bigness[n] = abs(jump)      
    return x, y, bigness

x, y, bigness = randomwalk(100)

plt.plot(x, y)
plt.show()

现在,如果我将倒数第二行更改为

plt.scatter(x, y, c=bigness)

然后我得到一堆具有所需颜色的点,但没有连接它们的线。相反,“绘图”功能没有单独着色的选项。

我想要来自“绘图”功能的线条,但来自“分散”功能的着色。我该怎么做呢?

4

2 回答 2

0

与其绘制整条线,不如根据大小用颜色绘制其线段。

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

def randomwalk(N):
    x, y, bigness = np.zeros((N)), np.zeros((N)), np.zeros((N))
    for n in range(0,N):
        angle = random.random() * 2*np.pi
        jump = np.random.normal(0, 50)

        x[n] = x[n-1] + (np.cos(angle) * jump)
        y[n] = y[n-1] + (np.sin(angle) * jump)
        bigness[n] = abs(jump)      
    return x, y, bigness

def random_color(bigness):
    return plt.cm.gist_ncar(bigness/100)

x, y, bigness = randomwalk(100)

xy = zip(x,y)
fig, ax = plt.subplots()
for start, stop, b in zip(xy[:-1], xy[1:], bigness):
    x, y = zip(start, stop)
    ax.plot(x, y, color=random_color(b))

plt.show()

美丽凌乱的结果

在此处输入图像描述

于 2016-03-24T06:49:44.640 回答
0

您可以通过以下方式手动创建LineCollection每个段并为其着色bigness

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
pairs = np.array(list(zip(x, y))).reshape(-1, 1, 2)
segments = np.concatenate((pairs[:-1], pairs[1:]), axis=1)
lc = mpl.collections.LineCollection(segments)
lc.set_array(bigness)
f, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale_view()
plt.show()

要指定非默认颜色图和规范,请将cmapnorm参数传递给mpl.collections.LineCollection.

于 2016-03-24T06:49:45.293 回答