user14385051
user14385051

Reputation:

How to change xlabel of figure in every loop

The code below plots a figure in evey loop and I want the average of each matrix printed as a x label. For example: ave is 40. I am not sure how to add ave of each image to 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()

Upvotes: 3

Views: 894

Answers (2)

ChaddRobertson
ChaddRobertson

Reputation: 653

You can do it like so:

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

To put a numerical value into a string, you can say '{}'.format(value). This can be done in numerous places using multiple {} brackets - where each bracket must be accompanied by its corresponding value in format().

More information can be found here:

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

To round off a value, you simply use round(), which takes two arguments: the value you would like to round off (in this case the average), followed by the number of decimals. Eg: round(ave, 3).

Upvotes: 0

Robin Thibaut
Robin Thibaut

Reputation: 640

The best way would be to use F-string formatting:

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

Note that to avoid numbers with many decimals, you can use

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

Upvotes: 1

Related Questions