python - 如何在 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。
如何编辑我的代码来实现这一点?谢谢!!!
解决方案
只需将 theta 变量添加到标题字符串
theta = 1
ax.set_title("Θ = %.i" % theta, fontsize=25)
通过保存文件做同样的事情
fig.savefig('Θ = ' + str(theta) +'.png')
推荐阅读
- sql - 活动日志表中 ID 列的最佳类型
- leaflet - 与折叠集成的传单
- java - 关于阻塞系统调用和潜在的竞争条件
- swift - 使用 ARKIT swift 检测平面后投影格式为 .usdz 的模型
- postgresql - 如何在sqlg中识别月份是否有30天或31天
- java - 更改舞台宽度/高度然后切换场景不会更新新场景中的 UI
- tcl - 如果调用 tkwait / vwait,则 Tcl_DoOneEvent 被阻塞
- parsing - 超过一个字节后的lua解析
- python - 我需要在 Python 的帮助下生成并保存 JPG 格式的 html/css 代码输出
- javascript - 获取数据表的主体作为 HTML 元素