Bueno, sé cómo agregar una barra de color a una figura, cuando he creado la figura directamente con matplotlib.pyplot.plt .
from matplotlib.colors import LogNorm import matplotlib.pyplot as plt import numpy as np # normal distribution center at x=0 and y=5 x = np.random.randn(100000) y = np.random.randn(100000) + 5 # This works plt.figure() plt.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar() Pero, ¿por qué lo siguiente no funciona y qué necesitaría agregar a la llamada de colorbar(..) para que funcione?
fig, ax = plt.subplots() ax.hist2d(x, y, bins=40, norm=LogNorm()) fig.colorbar() # TypeError: colorbar() missing 1 required positional argument: 'mappable' fig, ax = plt.subplots() ax.hist2d(x, y, bins=40, norm=LogNorm()) fig.colorbar(ax) # AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None' fig, ax = plt.subplots() h = ax.hist2d(x, y, bins=40, norm=LogNorm()) plt.colorbar(h, ax=ax) # AttributeError: 'tuple' object has no attribute 'autoscale_None'Estás casi allí con la tercera opción. Tienes que pasar un objeto mappable a la barra de colorbar para que sepa qué mapa de colores y límites darle a la barra de colores. Eso puede ser AxesImage o QuadMesh , etc.
En el caso dehist2D , la tupla devuelta en su h contiene ese mappable , pero también algunas otras cosas.
De los documentos :
Devoluciones: El valor devuelto es (recuentos, xedges, yedges, Imagen).
Entonces, para hacer la barra de colores, solo necesitamos la Image .
Para arreglar tu código:
from matplotlib.colors import LogNorm import matplotlib.pyplot as plt import numpy as np # normal distribution center at x=0 and y=5 x = np.random.randn(100000) y = np.random.randn(100000) + 5 fig, ax = plt.subplots() h = ax.hist2d(x, y, bins=40, norm=LogNorm()) fig.colorbar(h[3], ax=ax)Alternativamente:
counts, xedges, yedges, im = ax.hist2d(x, y, bins=40, norm=LogNorm()) fig.colorbar(im, ax=ax)