Python : 在图外添加 text/annotation (matplotlib)

Python : add text/annotation outside of plot (matplotlib)

我想在图外添加一个带有文本的框,其中我只说正值或负值的数量。每种类型的文本必须与图中数据的颜色相同,因此对于正数,它必须是红色,对于负数,它必须是蓝色。

这是我编写的代码:

text_plot = (f"number of positive neta : {nb_pos_neta}\nnumber of negative neta : {nb_neg_neta}")

fig, ax = plt.subplots(figsize =(10,7))
ax.scatter(time_det, neta, c = np.sign(neta), cmap="bwr", s=4, label='Rapport of polarisation')
plt.title('Evolution of rapport of polarisation - Aluminium')
plt.xlabel('Time [min]')
plt.ylabel('Rapport [-]')
plt.figtext(1.05, 0.5, text_plot, ha="right", fontsize=10, bbox={"facecolor":"white","alpha":0.5, "pad":5})
plt.tight_layout()
plt.savefig("Evolution of rapport of polarisation - (Aluminium).png")
plt.show()

结果如下:

这里的技巧是使用 matplotlib 的补丁来获取自定义图例。因为我需要生成一些假数据来让事情看起来很接近(并且真的不想深入研究像 neta 和 time_det 这样的东西,因为它们不是你问题的核心)我使用 numpy 的 wheresize 用于点的着色和计数。

import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches


# generate some fake data of a similar range
x = np.random.random(100)*3000
y = np.random.random(100)*1

count_red = np.size(np.where(np.reshape(y,-1) >= .5))
count_blue = np.size(np.where(np.reshape(y,-1)< .5))

col = np.where(x<0,'k',np.where(y<.5,'b','r'))

fig, ax = plt.subplots(figsize =(10,7))

red_patch = mpatches.Patch(color='red', label=count_red)
blue_patch = mpatches.Patch(color='blue', label=count_blue)

dist_off_right_spline = .95
dist_from_top_spline  = .6

plt.title('Evolution of rapport of polarisation - Aluminium')
plt.xlabel('Time [min]')
plt.ylabel('Rapport [-]')
plt.tight_layout()
plt.savefig("Evolution of rapport of polarisation - (Aluminium).png")

plt.legend(bbox_to_anchor=(dist_off_right_spline, dist_from_top_spline), 
           loc='upper left', handles=[red_patch, blue_patch])

plt.scatter(x, y, c=col, s=5, linewidth=1)
plt.show()

而且(减去 y 轴范围)为您提供的图像非常接近您指定的图像。