matplotlib Python:绘制负(x,y)坐标的频率

xmd2e60i  于 2022-11-15  发布在  Python
关注(0)|答案(1)|浏览(200)

我试图绘制从(0,0)开始的2D整数随机游走的频率。首先,我得到一个(x,y)坐标列表,其中一些是负的,我在正确绘制它们时遇到了问题。我知道我现在的尝试是错误的,因为(0,0)有时看起来根本不在随机游走中。
下面是我的尝试:
我们的想法是转置所有的(x,y)坐标,使它们位于第一象限,然后操纵extent上的轴将它们转置回原始形式。我这样做是为了避免在构建grid时进行不必要的列表操作,这会使绘图“跳跃”

# generate random walk
import random

def random_walk():

    a = 0
    b = 0
    while True:
        yield (a, b)

        i = random.choice([0, 1])
        if i == 0:
            a = random.choice([a-1, a+1])
        else:
            b = random.choice([b-1, b+1])

和阴谋本身的企图:

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

# generate random walk of length 1000
walk = list(itertools.islice(random_walk(), 0, 1000))

xy = list(zip(*walk))

x = list(xy[0])
y = list(xy[1])

ext = (min(x), max(x), min(y), max(y))

min_x = min(x)
min_y = min(y)

# transpose all x.- and y.-coordinates:

for i in range(len(x)):
    x[i] -= min_x

for i in range(len(y)):
    y[i] -= min_y

walk_new = list(zip(x,y))

grid = np.zeros((max(x) + 1, max(y) + 1))

# Put frequencies in grid:
for a,b in walk_new:
    grid[a][b] += 1

plt.imshow(grid)
plt.colorbar()
2ul0zpep

2ul0zpep1#

我确实注意到,当我运行代码时,原点(0,0)并没有像预期的那样显示在热图上。我让random_walk函数保持原样,但我认为在这里使用matplotlib的hist2d会更容易,因为(x,y)坐标完全按照您的意愿显示,而不需要转置您生成的坐标。

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

# generate random walk of length 1000
walk = list(itertools.islice(random_walk(), 0, 1000))

xy = list(zip(*walk))

x = list(xy[0])
y = list(xy[1])

heatmap, xedges, yedges = np.histogram2d(x, y, bins=[np.arange(min(x),max(x),1),np.arange(min(y),max(y),1)])
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.imshow(heatmap, origin='lower', extent=extent)

# set bins to be 1 unit apart since your (x,y) coordinates are integers
# plt.hist2d(x,y, bins=[np.arange(min(x),max(x),1),np.arange(min(y),max(y),1)])
plt.colorbar()
plt.show()

相关问题