如何在matplotlib.pyplot中使用带有hist2d的colorbar?

kni*_*ian 6 python matplotlib

我想做一些类似于http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html的内容,但我已经读到使用pylab代替python交互模式以外的代码是不好的做法所以我想这样做matplotlib.pyplot.但是,我无法弄清楚如何使用pyplot使这段代码工作.使用,pylab,给出的例子是

from matplotlib.colors import LogNorm
from pylab import *

#normal distribution center at x=0 and y=5
x = randn(100000)
y = randn(100000)+5

hist2d(x, y, bins=40, norm=LogNorm())
colorbar()
show()
Run Code Online (Sandbox Code Playgroud)

我尝试了很多

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
h1 = ax1.hist2d([1,2],[3,4])
Run Code Online (Sandbox Code Playgroud)

从这里我已经尝试了plt.colorbar(h1) plt.colorbar(ax1) plt.colorbar(fig) ax.colorbar()等等的一切,我无法得到任何工作.

总的来说,即使在阅读了http://matplotlib.org/faq/usage_faq.html之后,老实说我对pylab和pyplot之间的关系还不是很清楚.例如show()在pylab中似乎变成plt.show()了pyplot,但由于某种原因colorbar不成为plt.colorbar()

例如,

Imp*_*est 7

颜色条需要一个 ScalarMappable 对象作为它的第一个参数。plt.hist2d将 this 作为返回的元组的第四个元素返回。

h = hist2d(x, y, bins=40, norm=LogNorm())
colorbar(h[3])
Run Code Online (Sandbox Code Playgroud)

完整代码:

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

h = plt.hist2d(x, y, bins=40, norm=LogNorm())
plt.colorbar(h[3])
show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


phi*_*ilE 3

这应该可以做到:

from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
from numpy.random import randn

#normal distribution center at x=0 and y=5
x = randn(100000)
y = randn(100000)+5

H, xedges, yedges, img = plt.hist2d(x, y, norm=LogNorm())
extent = [yedges[0], yedges[-1], xedges[0], xedges[-1]]
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
im = ax.imshow(H, cmap=plt.cm.jet, extent=extent, norm=LogNorm())
fig.colorbar(im, ax=ax)
plt.show()
Run Code Online (Sandbox Code Playgroud)

请注意颜色条如何附加到“fig”,而不是“sub_plot”。这里还有一些其他的例子。请注意您还需要如何生成 ScalarMappable ,如此imshowAPI 中所述。