如何将Matplotlib 3D打印的XY栅格平面提升到Z=0?

2024-06-09 10:16:34 发布

您现在位置:Python中文网/ 问答频道 /正文

Multiple Histogram Plot

matplotlib中的默认三维栅格显示在z=0的下方。这使得我的参考线(红色)和柱状图看起来稍微偏离或在网格上方悬停。我希望它们看起来像是附着到网格上的

import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path
from matplotlib import cm
from scipy.stats import norm

open_file = Path('my_data_file.csv')
savefn   = Path('my_save_file.png')
nbins = 8
lsl   = 1.03
usl   = 1.05
data = np.zeros((30,8))


with open(open_file) as file:
    for x,line in enumerate(file):
        items = line.split(',')
        for y,item in enumerate(items):
            data[x,y] = float(item)           


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for z in range(data.shape[1]):#loop through the data
    ys = data[:,z]
    hist, bins = np.histogram(ys, bins=nbins)
    mu, std = norm.fit(ys) #get the mean and std
    xs = (bins[:-1] + bins[1:])/2
    x = np.linspace(min(xs), max(xs), 3*len(xs))#upsample the bins
    p = norm.pdf(x,mu,std)#fit the data to a normal pdf
    p = 3*p/sum(p) #normalize fits
    y = np.ones(len(p))*(z+1)
    ax.bar(xs, hist/sum(hist), zs=z+1, zdir='y', color=cm.Set1(z), ec='k', alpha=0.5,width=(xs[1]-xs[0]))#plot the histogram
    ax.plot(x,y,p,color=cm.Set1(z))#plot the fit


ax.plot((1.03,1.03),(1,8),0,color='r')#plot the lower spec limit
ax.plot([1.05,1.05],[1,8],0,color='r')#plot the upper spec limit

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.xlim(lsl-(lsl/1000),usl+(lsl/1000))
plt.ylim(1,8)
ax.set_zlim([0,0.4])

plt.show()
fig.savefig(fname= savefn,format="png",dpi=600)   

Tags: theimportdataplotmatplotlibasnpplt