首页 > 解决方案 > 如何在 ax.set_title 和 fig.savefig 中使用变量

问题描述

我的目标是绘制一个图形并给它一个标题并将其保存为 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。

如何编辑我的代码来实现这一点?谢谢!!!

标签: python

解决方案


只需将 theta 变量添加到标题字符串

theta = 1
ax.set_title("Θ = %.i" % theta, fontsize=25)

通过保存文件做同样的事情

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

推荐阅读