【问题标题】:How do I give the legend a background color in matplotlib?如何在 matplotlib 中为图例赋予背景颜色?
【发布时间】:2021-03-10 13:37:46
【问题描述】:

图例中的颜色与我的堆栈图上的颜色混合在一起。看起来,这似乎是默认设置(因为我没有触及任何颜色设置)。我将如何解决这个问题?有没有办法给我的图例一个背景颜色?我已经尝试过使用facecolor 参数。

这是我的代码:

from matplotlib import pyplot as plt

days = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# hours worked each day on the project 
dev1 = [8, 6, 5, 5, 4, 2, 1, 1, 0]
dev2 = [0, 1, 2, 2, 2, 4, 4, 4, 4]
dev3 = [0, 1, 1, 1, 2, 2, 3, 3, 4]



plt.style.use('fivethirtyeight')

labels = ['Developer 1', 'Developer 2', 'Developer 3']


plt.stackplot(days, dev1, dev2, dev3, labels=labels)

plt.legend(loc=(0.05, 0.07))
# plt.legend(loc=(0.05, 0.07), facecolor='white')    I have tried this as well
plt.title('My Awesome Stack Plot')
plt.tight_layout()
plt.show()

【问题讨论】:

  • 很奇怪。我得到this output
  • 会不会跟版本有关?我过去曾短暂使用过 matplotlib,这就是我记忆中的方式(默认情况下)。我还应该提到,我已经在 jupyter notebooks 和 jupyter lab 中尝试过这个

标签: python matplotlib jupyter-notebook jupyter-lab


【解决方案1】:

我解决了这个问题。 frameon=True 参数成功了。

plt.legend(loc=(0.05, 0.07),frameon=True)

【讨论】:

    【解决方案2】:

    添加:

    plt.legend.get_frame().set_facecolor('Color or Color_code')
    

    你可以在documentation找到它

    【讨论】:

    • 喜欢这个plt.legend(loc=(0.05, 0.07)).get_frame().set_facecolor('white')?那没有用
    猜你喜欢
    • 2019-04-16
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2014-09-08
    • 2021-09-30
    • 2014-02-10
    相关资源
    最近更新 更多