matplotlib子图中的图例位置

时间:2019-04-02 01:23:50

标签: matplotlib

我正在尝试在(6X3)网格上创建子图。我对图例的位置有疑问。图例是所有子图共有的。 lgend现在与y轴标签

重叠

我尝试删除了constrained_layout = True选项。但这在图例和子图之间保留了许多空白。

<script>
function clickCounter() {
  if (typeof(Storage) !== "undefined") {
    if (localStorage.clickcount) {
      localStorage.clickcount = Number(localStorage.clickcount)+1;
    } else {
      localStorage.clickcount = 1;
    }
    document.getElementById("result").innerHTML = "People have attempted but failed to help me <span id='recolor'>" + localStorage.clickcount + "</span> times.";

    if (localStorage.clickcount >= 100) {
      document.getElementById("recolor").style.color = "blue";
    }
  } else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support helping me.";
  }
}
</script>


<p><button onclick="clickCounter()" type="button"><b>HELP ME</b></button></p>
<div id="result"></div>

enter image description here

1 个答案:

答案 0 :(得分:1)

constrained_layout does not take figure legends into account。我目前在这里看到的最简单的选择是使用tight_layout使子图在图中很好地分布,然后 之后,手动为图例添加一些空间。

import matplotlib.pyplot as plt

fig, axs = plt.subplots(6, 3, figsize=(12,8), sharex=True, sharey=True,
                        constrained_layout=False)

labels = [f"Label {i}" for i in range(1,5)]

for ax in axs.flat:
    for i, lb in enumerate(labels):
        ax.plot([1,2], [0,i+1], label=lb)
    ax.set_xlabel("x label")
    ax.label_outer()

fig.tight_layout() 
fig.subplots_adjust(bottom=0.1)   ##  Need to play with this number.

fig.legend(labels=labels, loc="lower center", ncol=4)

plt.show()

enter image description here