使用`numpy.ndarray`在Matplotlib标题图中以指定格式绘制。

huangapple go评论70阅读模式
英文:

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)
&lt;class &#39;numpy.ndarray&#39;&gt;

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(&#39;Mean= &#39; + str(global_mean.data), fontsize=5, loc=&#39;right&#39;) 

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&#39;Mean =  {&quot;{:.2f}&quot;.format(arr.mean())}&#39;)
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&#39;Mean = {global_mean.data.item()}&#39;, fontsize=5, loc=&#39;right&#39;)

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&#39;Mean = {global_mean.data[()]}&#39;, fontsize=5, loc=&#39;right&#39;)

huangapple
  • 本文由 发表于 2023年3月31日 03:42:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75892356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定