use numpy.ndarray in matplotlib title plot with format
Question:
I am using Sara and matplotlib of some of work and I was wondering how could I use a class numpy.ndarray with specific format in the title of a plot I am doing.
The variable type is:
type(global_mean.data)
<class 'numpy.ndarray'>
and value:
global_mean.data
array(0.12485412, dtype=float32)
And I would to be in the title of the plot as:
Mean = 0.12
I tried something like this:
plt.title('Mean= ' + str(global_mean.data), fontsize=5, loc='right')
But it is not working.
Thanks for any suggestion
Answers:
import matplotlib.pyplot as plt
import numpy as np
arr = np.arange(20)
plt.plot(arr)
plt.title(f'Mean = {"{:.2f}".format(arr.mean())}')
plt.show()
You can get a scalar from a single-element array using the item
method:
plt.title(f'Mean = {global_mean.data.item()}', fontsize=5, loc='right')
This will work for a scalar array, a (1,)
array, a (1, 1)
array, etc. You can also index into a scalar array with ()
:
plt.title(f'Mean = {global_mean.data[()]}', fontsize=5, loc='right')
I am using Sara and matplotlib of some of work and I was wondering how could I use a class numpy.ndarray with specific format in the title of a plot I am doing.
The variable type is:
type(global_mean.data)
<class 'numpy.ndarray'>
and value:
global_mean.data
array(0.12485412, dtype=float32)
And I would to be in the title of the plot as:
Mean = 0.12
I tried something like this:
plt.title('Mean= ' + str(global_mean.data), fontsize=5, loc='right')
But it is not working.
Thanks for any suggestion
import matplotlib.pyplot as plt
import numpy as np
arr = np.arange(20)
plt.plot(arr)
plt.title(f'Mean = {"{:.2f}".format(arr.mean())}')
plt.show()
You can get a scalar from a single-element array using the item
method:
plt.title(f'Mean = {global_mean.data.item()}', fontsize=5, loc='right')
This will work for a scalar array, a (1,)
array, a (1, 1)
array, etc. You can also index into a scalar array with ()
:
plt.title(f'Mean = {global_mean.data[()]}', fontsize=5, loc='right')