我有代码生成并绘制随机游走就好了。但是,我想根据跳跃的大小为每条线着色。这是我的代码:
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)
然后我得到一堆带有所需颜色的点,但没有加入它们的线。相反,"情节"功能没有单独着色的选项。
我想要来自"剧情"功能,但来自"散射的着色"功能。我该怎么做?
答案 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()
美丽凌乱的结果
答案 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()
要指定非默认的色彩映射和规范,请将cmap
和norm
个参数传递给mpl.collections.LineCollection
。