将hexbin图添加到一起

时间:2012-08-02 09:49:07

标签: python matplotlib

我有四个己基图,它们都被标准化了。如何将它们组合在一起制作一个大的发行版? enter image description here 我尝试连接输入向量,然后创建hexbin图,但这会抛弃单个分布的规范化: enter image description here 那么如何添加单个hexbin分布,同时仍然维持归一化归一化?

我的代码的相关部分是:

def hex_plot(x,y,max_v):
  bounds = [0,max_v*m.exp(-(3**2)/2),max_v*m.exp(-2),max_v*m.exp(-0.5),max_v]   # The sigma bounds
  norm = mpl.colors.BoundaryNorm(bounds, ncolors=4)
  hex_ = plt.hexbin(x, y, C=None, gridsize=gridsize,reduce_C_function=np.mean,cmap=cmap,mincnt=1,norm=norm)
  print "Hex plot max: ",hex_.norm.vmax
  return hex_

gridsize=50
cmap = mpl.colors.ListedColormap(['grey','#6A92D4','#1049A9','#052C6E'])

hex_plot(x_tot,y_tot,34840)

谢谢。

1 个答案:

答案 0 :(得分:2)

我写了一些代码来完成你所追求的目标。根据您问题的片段,看起来您已经知道了分配方案给出的分布的高度(max_v),所以我在这个假设下工作。根据您应用此数据的情况,实际情况可能并非如此,在这种情况下,以下情况将会失败(它只会与您对分布高度的猜测/知识一样好)。出于我的示例数据的目的,我只是对max_v1max_v2的值进行了合理的猜测(基于快速绘图)。切换为评论版本定义的c1c2应该会重现原始问题。

import scipy
import matplotlib.pyplot as pyplot
import matplotlib.colors
import math

#need to know the height of the distributions a priori
max_v1 = 850 #approximate height of distribution 1 (defined below) with binning defined below
max_v2 = 400 #approximate height of distribution 2 (defined below) with binning defined below
max_v = max(max_v1,max_v2)

#make 2 differently sized datasets (so will require different normalizations)
#all normal distributions with assorted means/variances
x1 = scipy.randn(50000)/6.0+0.5
y1 = scipy.randn(50000)/3.0+0.5
x2 = scipy.randn(100000)/2.0-0.5
y2 = scipy.randn(100000)/2.0-0.5
#c1 = scipy.ones(len(x1)) #I don't assign meaningful weights here
#c2 = scipy.ones(len(x2)) #I don't assign meaningful weights here
c1 = scipy.ones(len(x1))*(max_v/max_v1) #highest distribution: no net change in normalization here
c2 = scipy.ones(len(x2))*(max_v/max_v2) #renormalized to same height as highest distribution

#define plot boundaries
xmin=-2.0
xmax=2.0
ymin=-2.0
ymax=2.0

#custom colormap
cmap = matplotlib.colors.ListedColormap(['grey','#6A92D4','#1049A9','#052C6E'])

#the bounds of 1sigma, 2sigma, etc. regions
bounds = [0,max_v*math.exp(-(3**2)/2),max_v*math.exp(-2),max_v*math.exp(-0.5),max_v]
norm = matplotlib.colors.BoundaryNorm(bounds, ncolors=4)

#make the hexbin plot
normalized = pyplot
hexplot = normalized.subplot(111)
normalized.hexbin(scipy.concatenate((x1,x2)), scipy.concatenate((y1,y2)), C=scipy.concatenate((c1,c2)), cmap=cmap, mincnt=1, extent=(xmin,xmax,ymin,ymax),gridsize=50, reduce_C_function=scipy.sum, norm=norm) #combine distributions and weights
hexplot.axis([xmin,xmax,ymin,ymax])
cax = pyplot.axes([0.86, 0.1, 0.03, 0.85])
clims = cax.axis()
cb = normalized.colorbar(cax=cax)
cax.set_yticklabels([' ','3','2','1',' '])
normalized.subplots_adjust(wspace=0, hspace=0, bottom=0.1, right=0.78, top=0.95, left=0.12)

normalized.show()

以下是没有修复的result(已使用注释c1c2),以及带有修复的result(代码为原样); (似乎我的低代表阻止我发布实际图像)。

希望有所帮助。