首页 > 解决方案 > Python - 从图表和图例中删除边框

问题描述

我有以下情节:

dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in 
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1))

显示这个:

在此处输入图像描述

我想删除图表和图例的所有边框,即图表周围的框(留下轴号,如 2015 和 6000 等)

我发现的所有示例都指的是脊椎和“斧头”,但是我还没有使用fig = plt.figure()etc构建图表。

有人知道该怎么做吗?

标签: pythonmatplotlib

解决方案


frameon=False您可以使用调用中的参数来删除图例的边框plt.legend()

如果您只有一个图形和轴处于活动状态,那么您可以使用plt.gca()来获取当前轴。或者df.plot.bar返回一个axes对象(我建议使用它,因为plt.gca()在处理多个数字时可能会让人感到困惑)。因此,您可以将脊椎的可见性设置为False

ax = dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in 
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1), frameon=False)

for spine in ax.spines:
    ax.spines[spine].set_visible(False)

    # Color of the spines can also be set to none, suggested in the comments by ScoutEU 
    # ax.spines[spine].set_color("None")

推荐阅读