英文:
use numpy.ndarray in matplotlib title plot with format
问题
I am using Sara and matplotlib for some of my work and I was wondering how to use a numpy.ndarray with a specific format in the title of a plot I am creating.
The variable type is:
type(global_mean.data)
<class 'numpy.ndarray'>
and the value is:
global_mean.data
array(0.12485412, dtype=float32)
I would like it 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's not working.
Thanks for any suggestions.
英文:
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
答案1
得分: 1
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()
英文:
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()
答案2
得分: 0
你可以使用 item
方法从单元素数组中获取标量值:
plt.title(f'Mean = {global_mean.data.item()}', fontsize=5, loc='right')
这对于标量数组、(1,)
数组、(1, 1)
数组等都适用。你也可以使用 ()
索引标量数组:
plt.title(f'Mean = {global_mean.data[()]}', fontsize=5, loc='right')
英文:
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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论