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

Python 如何更改每个循环中图形的xlabel,python,matplotlib,plot,seaborn,Python,Matplotlib,Plot,Seaborn,下面的代码在evey循环中绘制了一个图形,我希望每个矩阵的平均值打印为x标签。例如:ave是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

下面的代码在evey循环中绘制了一个图形,我希望每个矩阵的平均值打印为x标签。例如:
ave是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()
你可以这样做:

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()
中附带相应的值

更多信息可在此处找到:


要对值进行四舍五入,只需使用
round()
,它接受两个参数:要进行四舍五入的值(在本例中为平均值),后跟小数位数。例如:
round(ave,3)

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

plt.xlabel(f'ave is {ave}')
请注意,为了避免数字包含许多小数,可以使用

ave_round=np.round(ave, 3) # Round to 3 decimals

hmmm
plt.xlabel(“ave is…”+str(ave))
?谢谢。您能告诉我如何将平均数四舍五入到3位小数吗?正如其他答案所述,您也可以使用f字符串。但这取决于偏好。对于这个应用程序,您还可以使用字符串连接,而性能并不重要。但是,
format()
和f字符串在很大程度上被认为是最好的选择。因为我的平均值小于1,比如0.0003764。这种方法不适用于四舍五入
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()