简体   繁体   中英

2dHistogram: ValueError: too many values to unpack (expected 2)

I am trying to create a 2d Histogram from a scatter plot. But I get the error: ValueError: too many values to unpack (expected 2) using the code below

If I alter the input data to contain one list for the xy coordinates it works fine. It also works if I only select the first list in the 2dhistogram line. eg 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. 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. You can fix this pretty easily. Just change the lines that populate x and y to 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()]

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM