gpt4 book ai didi

python - 是否可以测试图例是否覆盖了 matplotlib/pyplot 中的任何数据

转载 作者:行者123 更新时间:2023-11-28 18:27:40 25 4
gpt4 key购买 nike

如果术语不正确,Python 初学者深表歉意。

我正在使用 legend(loc='best', ...) 方法,它在 99% 的时间内都有效。但是,当在单个图形上堆叠超过 9 个图(即下面示例中的 i>9)时,使用单独的标签,它默认居中并覆盖数据。

有没有办法在脚本中运行测试,如果图例覆盖任何数据点,该测试将给出真/假值?

非常简化的代码:

fig = plt.figure()
for i in data:
plt.plot(i[x, y], label=LABEL)
fig.legend(loc='best')
fig.savefig()

Example of legend covering data

最佳答案

一种方法是通过稍微更改限制在轴的底部/顶部/左侧或右侧添加一些额外空间(在您的情况下我更喜欢顶部或底部)。这样做会使图例适合数据下方。通过使用 ax.set_ylim(-3e-4, 1.5e-4) 设置不同的 y 限制来添加额外空间(上限大约是图中的值,-3 是估计值你需要的东西)。

您还需要做的是将图例拆分为更多列,创建图例时使用关键字ncol=N

Figure

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

ax = fig.add_subplot(111)

x = np.linspace(0, 1, 100)
y = 3.5 * x - 2
for i in range(9):
ax.plot(x, y + i / 10., label='iiiiiiiiiiii={}'.format(i))

ax.set_ylim(-3, 1.5)
ax.legend(loc='lower center', ncol=3) # ncol=3 looked nice for me, maybe you need to change this
plt.show()

编辑

另一个解决方案是将图例放在单独的轴上,就像我在下面的代码中所做的那样。数据图不需要关心为图例或任何东西腾出空间,你应该在下面的轴上有足够的空间来放置所有的线标签。如果您需要更多空间,可以轻松更改上轴与下轴的比例。

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()

ax = fig.add_subplot(211)
ax_leg = fig.add_subplot(212)

x = np.linspace(0, 1, 100)
y = 3.5 * x - 2
lines = []
for i in range(9): #for plotting the actual data
li, = ax.plot(x, y + i / 10., label='iiiiiiiiiiii={}'.format(i))
lines.append(li)

for line in lines: # just to make the legend plot
ax_leg.plot([], [], line.get_color(), label=line.get_label())
ax_leg.legend(loc='center', ncol=3, ) # ncol=3 looked nice for me, maybe you need to change this
ax_leg.axis('off')
fig.show()

enter image description here

关于python - 是否可以测试图例是否覆盖了 matplotlib/pyplot 中的任何数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40144729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com