我有一个用简短的 Python 代码运行的数值模拟。我想知道是否可以使用 tikzplotlib 生成包含整个模拟(而不仅仅是一张图片)的 .tex 文件。我问关于 SO 的问题。目前我唯一的想法是使用tikzplotlib生成动画的所有图片,并尝试直接在latex中寻找解决方案来制作动画。
这意味着我有一长串以下形式的 .tex 文件,我想使用 latex 制作动画。所有文件都具有相同的结构,它们仅在表的值上有所不同。是否可以将动画和 \input 命令循环或类似的东西结合起来?精确度:因为它是一个模拟,所以我必须处理一个相当大的文件列表(比如几千个)。
% This file was created with tikzplotlib v0.10.1.
\begin{tikzpicture}
\definecolor{darkgray176}{RGB}{176,176,176}
\definecolor{darkorange25512714}{RGB}{255,127,14}
\definecolor{steelblue31119180}{RGB}{31,119,180}
\begin{axis}[
tick align=outside,
tick pos=left,
x grid style={darkgray176},
xmajorgrids,
xmin=-0.45, xmax=9.45,
xtick style={color=black},
y grid style={darkgray176},
ymajorgrids,
ymin=-0.15, ymax=3.15,
ytick style={color=black}
]
\addplot [semithick, steelblue31119180]
table {%
0 2.20822381790091
1 2.20822381790091
2 2.20822381790091
3 2.20822381790091
4 2.20822381790091
5 0
6 0
7 0
8 0
9 0
};
\addplot [semithick, darkorange25512714]
table {%
0 0
1 0
2 0
3 0
4 0
5 2.20822381790091
6 2.20822381790091
7 2.20822381790091
8 2.20822381790091
9 2.20822381790091
};
\draw (axis cs:0.05,0.9) node[
scale=0.5,
anchor=base west,
text=black,
rotate=0.0
]{time = 0.1971943887775551};
\end{axis}
\end{tikzpicture}
编辑:这里是生成上述 tikz 代码的 python 代码示例(这里只有 500 帧,我很高兴能够使用动画来制作它!)。
import numpy as np
from scipy.integrate import solve_ivp
from matplotlib import pyplot as plt
from matplotlib import animation
# Sites
M = 10
sites = np.array(range(M))
# Particles
N = 3
# Right hand side
def lotka(t,x):
u = x[0:M]
v = x[M:]
dudt = u-u*u-u*v
dvdt = v-u*v-v*v
dxdt = np.concatenate((dudt,dvdt))
return dxdt
# Initial conditions
u0 = np.zeros(M)
v0 = np.zeros(M)
# Segregated
u0[0] = N
v0[-1] = N
if M%2 == 0:
for i in range(int(M/2)):
u0[i] = N
v0[M-1-i] = N
else:
for i in range(int(np.floor(M/2))-1):
u0[i] = N
v0[M-1-i] = N
x0 = np.concatenate((u0,v0))
# Solving the equation
nt = 500
t = np.linspace(0,0.2,nt)
x = solve_ivp(lotka,[0,4],x0,t_eval=t)
# Getting each species from the solution of solve_ivp
u = np.zeros((nt,M))
v = np.zeros((nt,M))
for i in range(nt):
u[i] = x.y.T[i][0:M]
v[i] = x.y.T[i][M:]
# Animation
data = [u, v]
fig = plt.figure()
ax = plt.axes()
ax.grid()
lines = [ax.plot(sites,u[0])[0], ax.plot(sites,v[0])[0]]
time_template = 'time = % s'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
lines.append(time_text)
import tikzplotlib
def animate(i,lines,data):
lines[0].set_ydata(data[0][i])
lines[1].set_ydata(data[1][i])
lines[2].set_text(time_template % t[i])
tikzplotlib.save("mytikz" + str(i) + ".tex")
return lines
anim = animation.FuncAnimation(fig,
animate,
#frames=200,
fargs=(lines,data),
interval=1,
blit=True)
plt.show()
答案1
Python 脚本输出编号文件,每个文件包含一个tikzpicture
代表动画序列一帧的环境。将它们组合成动画非常简单:
\documentclass[margin=3pt]{standalone}
\usepackage{pgfplots}
\usepackage{animate}
\begin{document}
\begin{animateinline}[controls]{24}
\multiframe{500}{i=0+1}{
\input{mytikz\i.tex}
}
\end{animateinline}
\end{document}