Python:matplotlib:按跳跃大小

时间:2016-03-24 06:33:27

标签: python matplotlib random-walk graph-coloring

我有代码生成并绘制随机游走就好了。但是,我想根据跳跃的大小为每条线着色。这是我的代码:

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)

然后我得到一堆带有所需颜色的点,但没有加入它们的线。相反,"情节"功能没有单独着色的选项。

我想要来自"剧情"功能,但来自"散射的着色"功能。我该怎么做?

2 个答案:

答案 0 :(得分: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()

美丽凌乱的结果

enter image description here

答案 1 :(得分: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