2015-09-15 27 views
4

我想用plt.hist2dplt.colorbar做些事情,并且我很难解决如何做到这一点。为了解释,我写了下面的例子:使plt.colorbar延伸到vmin/vmax之前和之后的步骤

import numpy as np 
from matplotlib import pyplot as plt 

x = np.random.random(1e6) 
y = np.random.random(1e6) 

plt.hist2d(x, y) 
plt.colorbar() 

plt.show() 

此代码生成的曲线,看起来像下面的图片。 2D histogram with colorbar plotted using pyplot

如果我生成直方图,理想情况下我希望颜色条超出数据的最大和最小范围以超出最大值和最小值的下一个步骤。在此问题的示例中,将以60为增量将色条范围从9660设置为10260.

如何强制plt.hist2dplt.colorbar设置颜色栏,以便将滴答分配给开始和结束绘制的彩条的?

回答

3

我认为这是你在找什么:

h = plt.hist2d(x, y) 
mn, mx = h[-1].get_clim() 
mn = 60 * np.floor(mn/60.) 
mx = 60 * np.ceil(mx/60.) 
h[-1].set_clim(mn, mx) 
cbar = plt.colorbar(h[-1], ticks=np.arange(mn, mx + 1, 60),) 

这给了像,

enter image description here

这也是很方便的使用代号从matplotlib.ticker,并使用tick_values tickers的方法,但为此目的,我认为上述是最方便的。

祝你好运!

+0

我没有想到要等到调用'plt.hist2d'来创建定位器之后,但这非常完美。然而,有几件事情关于这个解决方案:首先,如果任何一个bin都是空的(它将返回'h [0]'变量中的NaN),它就会失败,其次,它不会给出最大值和最小值的整数。在调用'locator.tick_values'之前,我可能会实际做'maximum = 60 * np.ceil(np.nanmax(h [0])/ 60.)'(以及类似的最小值)。但是谢谢你! –

+0

啊,实际上,这似乎并不适用于'MaxNLocator',我仍然看到延伸到最大勾号之外的颜色条。当我研究出为什么会发生这种情况时,我会在这里发帖... –

+1

感谢您发布这些信息,这让我想到,一旦我知道最大值和最小值是什么,我就可以在绘制它们之后更新对象。 (我在IDL学到的,所以面向对象的思想仍然有时候不见了。)我已经发布了一个单独的解决方案,它使用'h [3]'的'set_clim'属性在事实之后更新限制,然后绘制颜色通过使用此答案中的方法预定义的滴答。非常感谢你的帮助! –

2

巨大感谢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() 

导致这一点,这是我真正想要的:

enter image description here