2017-02-22 1 views
6

Nun, ich weiß, wie man einer Figur einen Farbbalken hinzufügt, wenn ich die Figur direkt mit matplotlib.pyplot.plt erstellt habe.Wie füge ich eine Farbleiste für ein hist2d Plot hinzu?

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() 

Aber warum funktioniert das folgende nicht, und was ich brauche, um den Ruf der colorbar(..) hinzuzufügen, damit es funktioniert.

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' 

Antwort

6

Sie sind fast mit der 3. Option. Sie müssen ein mappable Objekt an colorbar übergeben, damit es weiß, welche Colormap und Grenzen die Farbleiste geben. Das kann ein AxesImage oder QuadMesh usw.

Im Fall von hist2D sein, das Tupel zurückgegeben in Ihrem h enthält, dass mappable, aber auch einige andere Dinge auch.

Vom docs:

Rückkehr: Der Rückgabewert ist (zählt, xedges, yedges, Image).

Also, um die Farbleiste zu machen, brauchen wir nur die Image.

Code zu beheben:

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()) 
plt.colorbar(h[3], ax=ax) 

Alternativ:

counts, xedges, yedges, im = ax.hist2d(x, y, bins=40, norm=LogNorm()) 
plt.colorbar(im, ax=ax) 
+0

'fig.colorbar (im)' auch funktioniert, und scheint mit dem Rest der Antwort konsistenter. – ThomasH

Verwandte Themen