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

如何用Matplotlib将数字向量绘制成含数值的矩形?

在Matplotlib中绘制带数字的矩形框

当然有简便方法啦!用Matplotlib可以轻松实现这个效果——先画一个矩形边框,再把向量里的数字逐个放到框内合适的位置就行。下面是完整的可运行代码,你可以直接测试:

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

# 你的数字向量(也可以用np.random.randn(5).round(2).tolist()生成)
num_vector = [2.05, -1.57, 1.07, 1.37, 0.32]

# 创建画布和坐标轴
fig, ax = plt.subplots(figsize=(6, 2))

# 绘制矩形框:参数依次为左下角坐标、宽度、高度,可自定义边框和填充样式
rect = Rectangle((0, 0), 1, 1, edgecolor='black', facecolor='white', linewidth=2)
ax.add_patch(rect)

# 计算每个数字的位置:让数字在矩形内水平均匀分布、垂直居中
num_count = len(num_vector)
x_positions = [i/(num_count-1) for i in range(num_count)]
y_position = 0.5

# 逐个添加数字文本
for x, num in zip(x_positions, num_vector):
    ax.text(x, y_position, str(num), ha='center', va='center', fontsize=12)

# 调整坐标轴范围,确保矩形完整显示
ax.set_xlim(-0.05, 1.05)
ax.set_ylim(-0.05, 1.05)

# 隐藏坐标轴的刻度和边框,让视觉效果更干净
ax.set_xticks([])
ax.set_yticks([])
for spine in ax.spines.values():
    spine.set_visible(False)

plt.tight_layout()
plt.show()

关键细节说明:

  • 矩形样式自定义:你可以修改Rectangle的edgecolor(边框颜色)、facecolor(填充颜色)、linewidth(边框粗细)参数,匹配你想要的视觉风格。
  • 文本位置调整:ha='center'和va='center'确保数字在对应坐标点上水平、垂直居中;如果想调整数字间距,直接修改x_positions的计算逻辑即可。
  • 视觉优化:隐藏坐标轴元素是为了让焦点集中在矩形和数字上,如果你需要保留坐标轴,删掉最后几行隐藏代码就行。

内容的提问来源于stack exchange,提问作者CentAu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:15:57