如何在每个循环中更改图形的xlabel



下面的代码在每个循环中绘制了一个图形,我希望将每个矩阵的平均值打印为x标签。例如:ave is 40。我不知道如何将每个图像的ave添加到xlabel中。

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
a= np.random.randint(0, 100, size=(4, 600, 600))
for i in range(np.size(a,0)):
b=a[i,:,:]
ave=np.average(b)

plt.figure()
sns.heatmap(b, cmap='jet', square=True, xticklabels=False,
yticklabels=False)
plt.text(200,-20, "Relative Error", fontsize = 15, color='Black')
plt.xlabel("ave is...")
plt.show()

最好的方法是使用F字符串格式:

plt.xlabel(f'ave is {ave}')

请注意,为了避免有很多小数的数字,您可以使用

ave_round=np.round(ave, 3) # Round to 3 decimals
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
a= np.random.randint(0, 100, size=(4, 600, 600))
for i in range(np.size(a,0)):
b=a[i,:,:]
ave=np.average(b)
ave_round=np.round(ave, 3) # Round to 3 decimals

plt.figure()
sns.heatmap(b, cmap='jet', square=True, xticklabels=False,
yticklabels=False)
plt.text(200,-20, "Relative Error", fontsize = 15, color='Black')
plt.xlabel(f"ave is {ave_round}")
plt.show()

你可以这样做:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
a= np.random.randint(0, 100, size=(4, 600, 600))
for i in range(np.size(a,0)):
b=a[i,:,:]
ave=np.average(b)

plt.figure()
sns.heatmap(b, cmap='jet', square=True, xticklabels=False,
yticklabels=False)
plt.text(200,-20, "Relative Error", fontsize = 15, color='Black')
plt.xlabel("ave is {}".format(round(ave, 3)))
plt.show()

要将数值放入字符串中,可以说'{}'.format(value)。这可以在许多地方使用多个{}括号来完成,其中每个括号都必须伴随着其在format()中的相应值。

更多信息可以在这里找到:

https://www.w3schools.com/python/ref_string_format.asp

要取整一个值,只需使用round(),它有两个参数:要取整的值(在本例中为平均值(,然后是小数位数。例如:round(ave, 3)

最新更新