【问题标题】:2dHistogram: ValueError: too many values to unpack (expected 2)2dHistogram:ValueError:解包的值太多(预期为 2)
【发布时间】: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 中组合/展平列表列表的最简单方法是使用列表推导。您只需稍微调整填充xy 的行。或者,您可以只使用np.random.randint 来获取所需形状的随机 int 数组,而无需任何其他操作

标签: python pandas numpy histogram


【解决方案1】:

np.histogram2d 需要xy 坐标的平面列表,而不是列表列表。你可以很容易地解决这个问题。只需将填充xy 的行更改为flattening list comprehensions

x = [num for _ in range(10) for num in x_list()]
y = [num for _ in range(10) for num in y_list()]

或者,您可以跳过使用random.samplepartial 的整个复杂性,而只使用np.random.randint,它可以创建任何给定形状的随机整数数组:

x = np.random.randint(0, 80, size=100)
y = np.random.randint(0, 80, size=100)

【讨论】:

  • 谢谢@tel。我只是用列表列表复制我的输入数据。
猜你喜欢
  • 1970-01-01
  • 2017-08-29
  • 2020-05-11
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2017-12-14
  • 2017-07-15
相关资源
最近更新 更多