Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Cómo agregar una barra de colores para un gráfico hist2d

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'
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!