【问题标题】:Plot legend obscures plot lines in figure情节图例掩盖了图中的情节线
【发布时间】:2021-11-03 19:23:25
【问题描述】:

我正在使用matplotlib's gallery中的代码:

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)

plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')

plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')

plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,
             label='uplims=True, lolims=True')

upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,
             label='subsets of uplims and lolims')

plt.legend(loc='lower right')

并且,我在 jupyter 的终端中收到以下输出:

但是,在 matplotlib 库中,图例被很好地隐藏在错误栏限制选择之下:

我该如何解决这个问题?目前我的项目的其他一些情节也有同样的问题,传说阻碍了情节,到目前为止我没有取得任何进展。

【问题讨论】:

标签: python matplotlib plot legend


【解决方案1】:

对于此示例,只需在最后添加 plt.tight_layout() 似乎可以解决重叠问题。

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure()
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)

plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')

plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')

plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,
             label='uplims=True, lolims=True')

upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,
             label='subsets of uplims and lolims')


plt.legend(loc='lower right')
plt.tight_layout() # <- add this

但是,为了保持一致性,您可以调整图形的大小以避免图例重叠。

对于这个例子,它将是:

import numpy as np
import matplotlib.pyplot as plt


fig = plt.figure(figsize=(7,5)) # <- add a figsize
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 10)

plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')

plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')

plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,
             label='uplims=True, lolims=True')

upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,
             label='subsets of uplims and lolims')


plt.legend(loc='lower right')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-28
    • 2023-02-06
    • 1970-01-01
    • 2019-03-31
    • 2013-03-18
    • 2020-12-17
    • 2021-12-26
    • 2021-11-08
    相关资源
    最近更新 更多