You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Matplotlib中重现Gnuplot的with boxes绘图样式?

在Matplotlib中重现Gnuplot的with boxes绘图效果

我懂你想在Matplotlib里复刻Gnuplot那种with boxes的绘图样式——就是每个数据点对应一个从x轴(y=0)延伸到对应y值的矩形对吧?你提到用step方法是目前最接近的,但还达不到预期效果,那咱们来解决这个问题。

首先得明确Gnuplot的with boxes到底画了什么:每个数据点(x, y)会生成一个底部贴x轴、顶部到y值的矩形,默认宽度为1,中心对齐在对应的x坐标上。

在Matplotlib里,最直接的实现方式是用bar函数,它天生就是干这个的,和Gnuplot的boxes几乎完全匹配:

import matplotlib.pyplot as plt

x = range(3)
y = range(3)
# width=1对应Gnuplot默认的盒子宽度,align='center'让盒子中心对齐x坐标
plt.bar(x, y, width=1, align='center')
plt.show()

如果你非要用step方法来模拟的话,也可以通过配合fill_between来填充到x轴,实现类似的效果:

import matplotlib.pyplot as plt

x = range(3)
y = range(3)
# where='mid'让step的转折点对齐x坐标中心
plt.step(x, y, where='mid')
# 填充从x轴到step曲线的区域,模拟盒子的填充效果
plt.fill_between(x, 0, y, step='mid', alpha=0.5)
plt.show()

不过说实话,第一种用bar的方法更简洁,也更贴合Gnuplotwith boxes的原生效果。

内容的提问来源于stack exchange,提问作者serv-inc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:12:24