[英]2dHistogram: ValueError: too many values to unpack (expected 2)
I am trying to create a 2d Histogram from a scatter plot. 我正在尝试根据散点图创建2D直方图。 But I get the
error: ValueError: too many values to unpack (expected 2)
using the code below 但是我得到了
error: ValueError: too many values to unpack (expected 2)
使用下面的代码error: ValueError: too many values to unpack (expected 2)
If I alter the input data to contain one list for the xy coordinates it works fine. 如果我更改输入数据以包含一个xy坐标列表,则可以正常工作。 It also works if I only select the first list in the 2dhistogram line.
如果我仅选择2dhistogram行中的第一个列表,它也可以工作。 eg
zi, xi, yi = np.histogram2d(x[0], y[0], bins=bins)
. 例如
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)
The only post I could find about this suggested to try and change the x,y to a numpy array. 我可以找到的关于此的唯一文章建议尝试将x,y更改为numpy数组。 I tried this but still get the same error code.
我试过了,但仍然得到相同的错误代码。
zi, xi, yi = np.histogram2d(np.asarry(x), np.asarray(y), bins=bins)
Any other suggestions? 还有其他建议吗?
np.histogram2d
expects flat lists of x
and y
coordinates, not list-of-lists. np.histogram2d
需要x
和y
坐标的平面列表,而不是列表列表。 You can fix this pretty easily. 您可以轻松解决此问题。 Just change the lines that populate
x
and y
to flattening list comprehensions : 只需将填充
x
和y
的行更改为扁平化列表理解即可 :
x = [num for _ in range(10) for num in x_list()]
y = [num for _ in range(10) for num in y_list()]
Alternatively, you could skip the whole complexity of using random.sample
and partial
and just use np.random.randint
instead, which can create random integer arrays of any given shape: 另外,您可以跳过使用
random.sample
和partial
的整个复杂性,而只需使用np.random.randint
,它可以创建任何给定形状的随机整数数组:
x = np.random.randint(0, 80, size=100)
y = np.random.randint(0, 80, size=100)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.