Matplotlib子图图例在包含许多元素时与图表重叠。

huangapple go评论63阅读模式
英文:

Matplotlib Subplot Legends overlap with the Plot when containing many elements

问题

I have subplots with legends that contain a lot of elements. However the legends always overlap with the plots and I can't figure out how to add spacing between the legend and the plot or how to make them not overlap automatically in the first place. Is there any option that I would have to use to make them not overlap?

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(nrows=2, ncols=1)

for i, axe in enumerate(ax):
    for j in range(10):
        ax[i].plot(x, np.sin(x) + 0.1 * j, label="sin(x)")
    ax[i].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=7, ncol=4, mode="expand", borderaxespad=0., fontsize=10)
plt.tight_layout()
plt.show()

Matplotlib子图图例在包含许多元素时与图表重叠。

英文:

I have subplots with legends that contain a lot of elements. However the legends always overlap with the plots and I can't figure out how to add a spacing between legend and plot or how to make them not overlap automatically in the first place. Is there any option that I would have to use to make them not overlap?

import matplotlib.pyplot as plt
import numpy as np
 
x = np.linspace(0, 10, 100)
fig, ax = plt.subplots(nrows=2,ncols=1)

for i,axe in enumerate(ax):
    for j in range(10): 
        ax[i].plot(x, np.sin(x)+0.1*j, label="sin(x)")
    ax[i].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=7,ncol=4, mode="expand", borderaxespad=0.,fontsize = 10)
plt.tight_layout()
plt.show()

Matplotlib子图图例在包含许多元素时与图表重叠。

答案1

得分: 1

你可以使用ax[i].legend(loc=(0.0,1.04),...)来设置图例的位置。这些值是相对于坐标轴大小的x和y坐标。这个选项比默认的loc值更灵活。

英文:

You can set the location of the legend with ax[i].legend(loc=(0.0,1.04),...). The values are the x and y coordinates relative to the size of the axes. This option offers more flexibility than the default loc values.

huangapple
  • 本文由 发表于 2023年5月7日 06:28:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定