2017-02-22 16 views
6

Vâng, tôi biết cách thêm thanh màu vào hình, khi tôi đã tạo hình trực tiếp với matplotlib.pyplot.plt.Cách thêm thanh màu cho ô biểu đồ hist2d

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

Nhưng tại sao sau đây không làm việc, và những gì tôi sẽ cần phải thêm vào tiếng gọi của colorbar(..) để làm cho nó làm việc.

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' 

Trả lời

6

Bạn sắp hoàn tất tùy chọn thứ 3. Bạn phải chuyển đối tượng mappable tới colorbar để biết colormap và giới hạn nào cho thanh màu. Đó có thể là một AxesImage hoặc QuadMesh vv

Trong trường hợp của hist2D, các tuple trả lại trong h của bạn có chứa rằng mappable, nhưng cũng có một số thứ khác nữa.

Từ docs:

Returns: Giá trị trả về là (đếm, xedges, yedges, Hình ảnh).

Vì vậy, để tạo thanh màu, chúng tôi chỉ cần Image.

Để khắc phục mã của bạn:

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) 

Hoặc:

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

'fig.colorbar (im) 'cũng làm việc, và dường như phù hợp hơn với phần còn lại của câu trả lời. – ThomasH

Các vấn đề liên quan