Skip to main content
 首页 » 编程设计

python之不根据前 x 值插值绘制数据

2025年04月02日9jpfss

我目前正在做一些粒子追踪。因此我想绘制通过粒子的分布和累积函数。

当我绘制分布时,我的绘图总是提前一个时间步开始。 有没有一种方法可以将事件绘制为一种峰值,而不在 x 轴上进行任何插值?

附上简短的示例数据...

time = [ 0.,1.,2.,3.,4.,5.,6.,7.,8.,9.] 
counts = [0,0,1,0,2,0,0,0,1,0] 
cum = [ 0.,0.,0.25,0.25,0.75,0.75,0.75,0.75,1.,1.] 
 
ax1 = plt.subplot2grid((1,2), (0, 0), colspan=1) 
ax1.plot(time, counts, "-", label="Density") 
ax1.set_xlim([0,time[-1]]) 
ax1.legend(loc = "upper left", frameon = False) 
ax1.grid() 
 
ax2 = plt.subplot2grid((1,2), (0, 1), rowspan=1) 
ax2.step(time, cum, "r",where='post', label="Sum") 
ax2.legend(loc = "upper left", frameon = False) 
ax2.set_ylim([-0.05,1.05]) 
ax2.set_xlim([0,time[-1]]) 
ax2.grid() 
 
plt.suptitle("Particle distribution \n") 
plt.show() 

感谢您的帮助!

请您参考如下方法:

没有插值;使用 plot(.., '-'),matplotlib 只是“连接点”(您提供的数据坐标)。要么不要画线并使用标记,例如:

ax1.plot(time, counts, "o", label="Density") 

或者使用例如bar() 绘制“峰”:

ax1.bar(time, counts, width=0.001) 

edit:绘制 bar() 并不理想,因为您绘制的不是单独的线条,而是非常小的条形图。原来matplotlib其实有一个绘制峰的函数:stem():

ax1.stem(time, counts, label="Density") 

结果是: