如何自定义以观测数为标签的散点图图例

问题描述 投票:0回答:2

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

这是我写的代码:

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

这是结果:

python matplotlib plot scatter-plot legend-properties
2个回答
1
投票

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

where
size
重构了点的着色和计数。

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 轴范围)为您提供了非常接近您指定的图像。


0
投票

为什么不只使用标准选择和标签?

x = np.arange(100)
y = np.random.randn(100)
fig, ax = plt.subplots()
ax.plot(x[y>=0], y[y>=0], 'r.', ls='none', label=f"≥0: {len(y[y>=0])}")
ax.plot(x[y<0], y[y<0], 'b.', ls='none', label=f"<0: {len(y[y<0])}")
ax.legend()

© www.soinside.com 2019 - 2024. All rights reserved.