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

如何在Matplotlib图表顶部添加指定位置的t=0时间戳及多帧时间计数器?

解决方案

一、在图表顶部添加静态时间戳t=0

完全可以实现,只需在你的绘图代码末尾(plt.show()之前)添加一行文本绘制代码,指定位置和样式即可:

修改后的核心代码片段

# 在图表顶部中央位置添加t=0时间戳
aPe.text(0.5, 1.05, 't=0', transform=aPe.transAxes, ha='center', fontsize=12, weight='bold')

plt.axis('off')
plt.show()

参数说明

  • transform=aPe.transAxes:使用坐标轴相对坐标(范围0-1),避免图表尺寸变化时位置偏移
  • 0.5:x轴方向的中央位置
  • 1.05:y轴方向超出图表顶部的位置,确保文本显示在图表上方
  • ha='center':文本水平居中对齐

二、实现逐帧递增的时间计数器

Python结合Matplotlib的animation模块可以轻松实现逐帧更新的时间计数器,以下是完整的实现代码:

完整动画代码

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
from matplotlib.colors import Normalize
from matplotlib import cm
import math
from numpy import nan
from matplotlib.animation import FuncAnimation

def init():
    n=3
    arMax=[]
    arMin=[]

    N=2*n*(n-1)
    J = np.array([[]])

    Pe=np.array([[394.20560747663563, 408.7929050665396 , 419.132709901089  ,
            398.95097406721044, 403.81198021076113, 430.00914784982064,
            424.50127213826016, 453.54817733128607, 441.4651085668709 ,
            447.42507960635163, 413.8982415602072 , 390.3025816600353 ]])
        
    C1 = nan
    for i in J[0]:
        Pe = np.insert(Pe, i, [C1], axis=1)

    for i in range(len(Pe)):
        Max=max(Pe[i])
        Min=min(Pe[i])
        arMax.append(Max)
        arMin.append(Min)

    a=min(arMin)
    b=max(arMax)
    Amax= math.ceil(b)
    Amin= math.floor(a)

    color = cm.get_cmap('Dark2')
    norm = Normalize(vmin=Amin, vmax=Amax)
    color_list = [color(((Pe[0,i])-Amin)/(Amax-Amin)) for i in range(len(Pe[0]))]
        
    id = 0
    for j in range(n):
        for k in range(n-1):
            aPe.hlines(200+200*(n-j-1)+5*n, 200*(k+1)+5*n, 200*(k+2)+5*n, zorder=0, colors=color_list[id])
            id += 1

        for i in range(n):
            rect = mpl.patches.Rectangle((200+200*i, 200+200*j), 10*n, 10*n, linewidth=1, edgecolor='black', facecolor='black')
            aPe.add_patch(rect)
            if j < n-1:
                aPe.vlines(200+200*i+5*n, 200*(n-1-j)+5*n, 200*(n-j)+5*n, zorder=0, colors=color_list[id])
                id += 1

    cb = fig.colorbar(cm.ScalarMappable(cmap=color, norm=norm), ticks=np.arange(Amin, Amax+len(color.colors), len(color.colors)))
    cb.set_ticks(np.arange(Amin, Amax+1, (Amax-Amin)/8).astype(np.int64))
    cb.set_label("Entry pressure (N/m$^{2}$)")
    aPe.set_xlim(left=0, right=220*n)
    aPe.set_ylim(bottom=0, top=220*n)
    plt.axis('off')
    
    # 创建可更新的时间戳文本对象
    global time_text
    time_text = aPe.text(0.5, 1.05, 't=0', transform=aPe.transAxes, ha='center', fontsize=12, weight='bold')
    return time_text,

def update(frame):
    # 每帧更新时间戳文本
    time_text.set_text(f't={frame}')
    return time_text,

fig,aPe = plt.subplots(1)
# 创建动画:frames设置总帧数,interval设置帧间隔(毫秒)
ani = FuncAnimation(fig, update, frames=np.arange(0, 10), init_func=init, blit=True, interval=500)
plt.show()

关键说明

  • FuncAnimation:Matplotlib的动画核心类,负责逐帧调用更新函数
  • init_func:初始化静态图表内容(只执行一次)
  • update:每帧执行的函数,修改时间戳文本内容
  • frames:指定计数器的取值范围(示例中为0到9)
  • interval:控制帧之间的间隔时间(单位:毫秒)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:06:32