Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python和matplotlib,事件的2D直方图与事件概率x轴和y轴的1D条形图不对齐_Python_Matplotlib_Bar Chart_Histogram2d - Fatal编程技术网

使用python和matplotlib,事件的2D直方图与事件概率x轴和y轴的1D条形图不对齐

使用python和matplotlib,事件的2D直方图与事件概率x轴和y轴的1D条形图不对齐,python,matplotlib,bar-chart,histogram2d,Python,Matplotlib,Bar Chart,Histogram2d,为了可视化两个变量对事件发生的影响,我想使用matplotlib绘制二维直方图 在我的测试案例中,事件是“愿望成真”,变量x是流星的数量,y是仙女教母的参与。我想做的是绘制一个二维柱状图,为一箱箱的流星和仙女教母实现愿望。然后,在每个轴旁边,我想展示一个愿望实现的概率,event/(event+nonevent),对于每个坠落的星星和仙女教母的箱子(1D条形图,包含每个柱状图箱子的概率)。条形图仓应与二维柱状图仓相对应并与之对齐。然而,条形图和柱状图之间似乎有轻微的偏差 为了正确对齐条形图,与第

为了可视化两个变量对事件发生的影响,我想使用matplotlib绘制二维直方图

在我的测试案例中,事件是“愿望成真”,变量
x
是流星的数量,
y
是仙女教母的参与。我想做的是绘制一个二维柱状图,为一箱箱的流星和仙女教母实现愿望。然后,在每个轴旁边,我想展示一个愿望实现的概率,event/(event+nonevent),对于每个坠落的星星和仙女教母的箱子(1D条形图,包含每个柱状图箱子的概率)。条形图仓应与二维柱状图仓相对应并与之对齐。然而,条形图和柱状图之间似乎有轻微的偏差

为了正确对齐条形图,与第一个和最后一个箱子边缘相对应的轴限制的设置会起作用吗?一旦设置了这些限制,我是否可以将料仓中心作为轴上的位置(相对于索引)送入
plt.bar()

我的代码和生成的图像如下所示:

import numpy as np
import matplotlib.pyplot as plt
from numpy import linspace
import cubehelix

# Create random events and non-events
x_noneve = 3.*np.random.randn(10000) +22.
np.random.seed(seed=41)

y_noneve = np.random.randn(10000)
np.random.seed(seed=45)

x_eve = 3.*np.random.randn(1000) +22.
np.random.seed(seed=33)

y_eve = np.random.randn(1000)

x_all = np.concatenate((x_eve,x_noneve),axis=0)
y_all = np.concatenate((y_eve,y_noneve),axis=0)

# Set up default x and y limits
xlims = [min(x_all),max(x_all)]
ylims = [min(y_all),max(y_all)]

# Set up your x and y labels
xlabel = 'Falling Star'
ylabel = 'Fairy Godmother'

# Define the locations for the axes
left, width = 0.12, 0.55
bottom, height = 0.12, 0.55
bottom_h = left_h = left+width+0.03

# Set up the geometry of the three plots
rect_wishes = [left, bottom, width, height]  # dimensions of wish plot
rect_histx  = [left, bottom_h, width, 0.25]  # dimensions of x-histogram
rect_histy  = [left_h, bottom, 0.25, height] # dimensions of y-histogram

# Set up the size of the figure
fig = plt.figure(1, figsize=(9.5,9))
fig.suptitle('Wishes coming true', fontsize=18, fontweight='bold')

cx1 = cubehelix.cmap(startHue=240,endHue=-300,minSat=1,maxSat=2.5,minLight=.3,maxLight=.8,gamma=.9)

# Make the three plots
axWishes = plt.axes(rect_wishes) # wishes plot
axStarx = plt.axes(rect_histx)   # x bar chart  
axFairy = plt.axes(rect_histy)   # y bar chart 

# Define the number of bins
nxbins = 50
nybins = 50
nbins = 100

xbins = linspace(start = xlims[0], stop = xlims[1], num = nxbins)
ybins = linspace(start = ylims[0], stop = ylims[1], num = nybins)
xcenter = (xbins[0:-1]+xbins[1:])/2.0
ycenter = (ybins[0:-1]+ybins[1:])/2.0

delx    = np.around(xbins[1]-xbins[0], decimals=2,out=None)
dely    = np.around(ybins[1]-ybins[0], decimals=2,out=None)

H, xedges,yedges = np.histogram2d(y_eve,x_eve,bins=(ybins,xbins))
X = xcenter
Y = ycenter
H = np.where(H==0,np.nan,H) # Remove 0's from plot

# Plot the 2D histogram
cax = (axWishes.imshow(H, extent=[xlims[0],xlims[1],ylims[0],ylims[1]],
       interpolation='nearest', origin='lower',aspect="auto",cmap=cx1))

#Plot the axes labels
axWishes.set_xlabel(xlabel,fontsize=14)
axWishes.set_ylabel(ylabel,fontsize=14)

#Set up the plot limits
axWishes.set_xlim(xlims)
axWishes.set_ylim(ylims)

#Set up the probability bins
x_eve_hist, xoutbins    = np.histogram(x_eve, bins=xbins) 
y_eve_hist, youtbins    = np.histogram(y_eve, bins=ybins) 

x_noneve_hist, xoutbins    = np.histogram(x_noneve, bins=xbins) 
y_noneve_hist, youtbins    = np.histogram(y_noneve, bins=ybins) 

probax = [eve/(eve+noneve+0.0) if eve+noneve>0 else 0 for eve,noneve in zip(x_eve_hist,x_noneve_hist)]
probay = [eve/(eve+noneve+0.0) if eve+noneve>0 else 0 for eve,noneve in zip(y_eve_hist,y_noneve_hist)]

probax = probax/np.sum(probax)
probay = probay/np.sum(probay)

probax = np.round(probax*100., decimals=0, out=None)
probay = np.round(probay*100., decimals=0, out=None)

#Plot the bar charts  

#Set up the limits
axStarx.set_xlim( xlims[0], xlims[1])
axFairy.set_ylim( ylims[0], ylims[1])

axStarx.bar(xcenter, probax, align='center', width =delx, color = 'royalblue')
axFairy.barh(ycenter,probay,align='center', height=dely, color = 'mediumorchid')

#Show the plot
plt.show()


虽然我的原始代码是功能性的,但2D histo和条形图的界限没有使用直方图箱定义。因此,对箱子的任何更改都会导致图形对齐不良。为了确保图形的限制始终对应于直方图箱的限制,我更改了

cax = (axWishes.imshow(H, extent=[xmin,xmax,ymin,ymax],
       interpolation='nearest', origin='lower',aspect="auto",cmap=cx1))


有关信息,条形图可以接受沿轴的索引或值作为条形图位置。当条形对应于料仓而非分类变量时,设置轴限制和正确定义条形宽度非常重要。这些都是通过histo自动完成的。但是,如果您希望探索除bin成员数以外的变量,则必须使用条形图并手动定义限制

大家好,欢迎来到SO。你的代码有什么问题吗?这似乎奏效了,你在征求人们对什么更好、什么不更好的意见。这不一定就是这么回事。顺便说一句,情节非常好;)谢谢:)并对任何误用SO表示歉意(如你所见,我是新来的)。我在这段代码中遇到的主要问题是(I)获得条形图箱的正确对齐-我想确保设置x y轴限制,然后使用中心将导致条形图和二维历史的完美对齐,以及(ii)使用imshow。在这段代码的一个更复杂的版本中,我尝试了imshow,其中origin为“upper”和“lower”,但与柱状图相比,它总是看起来颠倒的。不幸的是,我无法发布更复杂的版本。你看到了吗:?这可能有助于验证限制,谢谢!不用担心:)祝你好运。
cax = (axWishes.imshow(H, extent=[xbins[0],xbins[-1],ybins[0],ybins[-1]],
       interpolation='nearest', origin='lower',aspect="auto",cmap=cx1))
axStarx.set_xlim( xlims[0], xlims[1])
axFairy.set_ylim( ylims[0], ylims[1])
axStarx.set_xlim(axWishes.get_xlim()) 
axFairy.set_ylim(axWishes.get_ylim())