【发布时间】:2018-04-19 04:39:56
【问题描述】:
我正在尝试从散点图创建二维直方图。但我使用下面的代码得到error: ValueError: too many values to unpack (expected 2)
如果我更改输入数据以包含 xy 坐标的一个列表,它工作正常。如果我只选择 2dhistogram 行中的第一个列表,它也可以工作。例如
zi, xi, yi = np.histogram2d(x[0], y[0], bins=bins).
import matplotlib.pyplot as plt
import numpy as np
import random
from functools import partial
##create list of lists (x,y coordinates)
x_list = partial(random.sample, range(80), 10)
y_list = partial(random.sample, range(80), 10)
x = [x_list() for _ in range(10)]
y = [y_list() for _ in range(10)]
fig, ax = plt.subplots()
ax.set_xlim(0,80)
ax.set_ylim(0,80)
bins = [np.linspace(*ax.get_xlim(), 80),
np.linspace(*ax.get_ylim(), 80)]
##error occurs in this line
zi, xi, yi = np.histogram2d(x, y, bins=bins)
zi = np.ma.masked_equal(zi, 0)
ax.pcolormesh(xi, yi, zi.T)
ax.set_xticks(bins[0], minor=True)
ax.set_yticks(bins[1], minor=True)
ax.grid(True, which='minor')
scat = ax.scatter(x, y, s = 1)
我能找到的唯一一篇建议尝试将 x,y 更改为 numpy 数组。我试过了,但仍然得到相同的错误代码。
zi, xi, yi = np.histogram2d(np.asarry(x), np.asarray(y), bins=bins)
还有其他建议吗?
【问题讨论】:
-
来自 histogram2d 文档: x : array_like, shape (N,) 包含要进行直方图绘制的点的 x 坐标的数组。 y : array_like, shape (N,) ,但您的 x 和 y 形状似乎是 (10,10)
-
所以我可以将所有 xy 坐标合并到一个列表中。谢谢@user1319128
-
在 Python 中组合/展平列表列表的最简单方法是使用列表推导。您只需稍微调整填充
x和y的行。或者,您可以只使用np.random.randint来获取所需形状的随机 int 数组,而无需任何其他操作
标签: python pandas numpy histogram