1

I'm trying to realize a colorbar for a 2D Histogram in Python.

Here is my code:

import matplotlib.pyplot as plt
import numpy as np


mean=[0,0]
cov=[[1,1],[1,2]]
x,y = np.random.multivariate_normal(mean,cov,10000).T

fig=plt.figure()
ax=plt.axes()

cax=ax.hist2d(x,y,bins=30,cmap="Blues")
cb=fig.colorbar(cax)
cb.ax.set_label("counts in bin")

plt.show()

But here I get the error message:

AttributeError: 'tuple' object has no attribute 'autoscale_None'

What am I doing wrong? I want to to this object oriented and thus I want to use the methods of ax and fig rather than using the functions of plt.

I hope somebody can help me...

2Obe
  • 3,570
  • 6
  • 30
  • 54

1 Answers1

6

ax.hist2d returns a tuple:

The return value is (counts, xedges, yedges, Image).

You only need the image for your colorbar:

cb=fig.colorbar(cax[3])
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139