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

3
下面的代码在每个循环中绘制一个图形,我希望每个矩阵的平均值作为x标签打印出来。例如:ave is 40。我不确定如何将每个图像的平均值添加到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()

嗯嗯,plt.xlabel("ave is..."+str(ave)) - StupidWolf
2个回答

1

最好的方法是使用 F-string 格式化:

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()

由于我的平均值小于1,例如0.0003764。这种方法无法进行四舍五入。 - user14385051

0
你可以这样做:
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)

谢谢。您能告诉我如何将平均值四舍五入到小数点后三位吗? - user14385051
1
正如其他答案所述,您也可以使用f-strings。但这取决于个人喜好。对于此应用程序,您还可以使用字符串连接,性能并不重要。然而,format()和f-strings通常被认为是最佳选择。 - ChaddRobertson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接