Python 如何在ax.set_title和fig.savefig中使用变量

Python 如何在ax.set_title和fig.savefig中使用变量,python,Python,我的目标是绘制一个图形,给它一个标题,并将其保存为png文件 #set the number of variable Θ Θ = 1 #give the title ax.set_title("Θ = ", fontsize=25) plt.show() fig.savefig('D:/Θ = .png') 例如,我首先绘制一个图形 from matplotlib import pyplot as plt import numpy as np from skimage import me

我的目标是绘制一个图形,给它一个标题,并将其保存为png文件

#set the number of variable Θ
Θ = 1

#give the title
ax.set_title("Θ = ", fontsize=25)


plt.show()
fig.savefig('D:/Θ = .png')
例如,我首先绘制一个图形

from matplotlib import pyplot as plt
import numpy as np
from skimage import measure


# Set up mesh
n = 100

x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
z = np.linspace(-3,3,n)
X, Y, Z =  np.meshgrid(x, y, z)

# Create cardioid function
def f_heart(x,y,z):
    F = 320 * ((-x**2 * z**3 -9*y**2 * z**3/80) +
               (x**2 + 9*y**2/4 + z**2-1)**3)
    return F

# Obtain value to at every point in mesh
vol = f_heart(X,Y,Z)

# Extract a 2D surface mesh from a 3D volume (F=0)
verts, faces ,_ ,_ = measure.marching_cubes_lewiner(vol, 0, spacing=(0.1, 0.1, 0.1))


# Create a 3D figure
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111, projection='3d')

# Plot the surface
ax.plot_trisurf(verts[:, 0], verts[:,1], faces, verts[:, 2],
                cmap='Spectral', lw=1)

# Change the angle of view and title
ax.view_init(15, -15)
现在,我想使用一个变量作为绘图的标题,并将其保存为png文件

#set the number of variable Θ
Θ = 1

#give the title
ax.set_title("Θ = ", fontsize=25)


plt.show()
fig.savefig('D:/Θ = .png')
我希望这段代码可以给我一个标题为Θ=1的绘图(或我为Θ设置的其他值),并将绘图保存在D://处,名称为Θ=1

如何编辑代码以实现这一点?
谢谢你

只需将θ变量添加到标题字符串中即可

theta = 1
ax.set_title("Θ = %.i" % theta, fontsize=25)
通过保存文件,也可以这样做

fig.savefig('Θ = ' + str(theta) +'.png')

你能教我当θ=pi/2时怎么做吗?(一个浮点数)@Joanne你的意思是将pi/2设置为标题中的符号?是的~我想要一个标题“Θ=pi/2”。还有一个名为Θ=pi/2的文件。png@Joanne
ax.set\u title($\Theta$=$\pi/2$”,fontsize=25)
但是你不能用包含
/
@Joanna的名称保存文件如果我的答案有用,如果你放弃我的箭头,那就好了:)