我想使用 matplotlib 绘制一个二维直方图,以便可视化两个变量对事件发生的影响。
在我的测试案例中,事件是“愿望成真”,变量x
是流星的数量,y
是仙女教母的参与。我想做的是为流星和仙女教母的垃圾箱绘制一个愿望成真的二维直方图。然后在每个轴旁边,我想显示每个流星和仙女教母箱(包含每个直方图箱的概率的一维条形图)实现愿望的概率,事件/(事件+非事件)。条形图箱应对应于二维直方图箱并与之对齐。但是,条形图和直方图箱之间似乎存在轻微的错位。
为了正确对齐条形图,对应于第一个和最后一个 bin 边缘的轴限制设置是否有效?一旦设置了这些限制,我可以将 bin 中心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()