巨大感谢farenorth,谁得到我以正确的方式思考这个问题,我想出了一个功能,get_colour_bar_ticks
:
def get_colour_bar_ticks(colourbar):
import numpy as np
# Get the limits and the extent of the colour bar.
limits = colourbar.get_clim()
extent = limits[1] - limits[0]
# Get the yticks of the colour bar as values (ax.get_yticks() returns them as fractions).
fractions = colourbar.ax.get_yticks()
yticks = (fractions * extent) + limits[0]
increment = yticks[1] - yticks[0]
# Generate the expanded ticks.
if (fractions[0] == 0) & (fractions[-1] == 1):
return yticks
else:
start = yticks[0] - increment
end = yticks[-1] + increment
if fractions[0] == 0:
newticks = np.concatenate((yticks, [end]))
elif fractions[1] == 1:
newticks = np.concatenate(([start], yticks))
else:
newticks = np.concatenate(([start], yticks, [end]))
return newticks
有了这个功能,那么我可以这样做:
from matplotlib import pyplot as plt
x = np.random.random(1e6)
y = np.random.random(1e6)
h = plt.hist2d(x, y)
cbar = plt.colorbar()
ticks = get_colour_bar_ticks(cbar)
h[3].set_clim(ticks[0], ticks[-1])
cbar.set_clim(ticks[0], ticks[-1])
cbar.set_ticks(ticks)
plt.show()
导致这一点,这是我真正想要的:
我没有想到要等到调用'plt.hist2d'来创建定位器之后,但这非常完美。然而,有几件事情关于这个解决方案:首先,如果任何一个bin都是空的(它将返回'h [0]'变量中的NaN),它就会失败,其次,它不会给出最大值和最小值的整数。在调用'locator.tick_values'之前,我可能会实际做'maximum = 60 * np.ceil(np.nanmax(h [0])/ 60.)'(以及类似的最小值)。但是谢谢你! –
啊,实际上,这似乎并不适用于'MaxNLocator',我仍然看到延伸到最大勾号之外的颜色条。当我研究出为什么会发生这种情况时,我会在这里发帖... –
感谢您发布这些信息,这让我想到,一旦我知道最大值和最小值是什么,我就可以在绘制它们之后更新对象。 (我在IDL学到的,所以面向对象的思想仍然有时候不见了。)我已经发布了一个单独的解决方案,它使用'h [3]'的'set_clim'属性在事实之后更新限制,然后绘制颜色通过使用此答案中的方法预定义的滴答。非常感谢你的帮助! –