英文:
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()
英文:
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()
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论