matplotlib 调整legend的位置 和 单独把legend拿出来
1. 把legend放在图外面
font2 = {'family': 'Times New Roman',
'weight': 'normal',
'size': 12,
}
ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1),
fancybox=True, shadow=True, ncol=3, prop=font2)
效果:
官方文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.legend.html?highlight=legend#matplotlib.axes.Axes.legend
参考链接:https://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot
2. 单独画legend
参考链接(在最下面):https://stackoverflow.com/questions/4534480/get-legend-as-a-separate-picture-in-matplotlib
It is possible to use axes.get_legend_handles_labels to get the legend handles and labels from one axes object and to use them to add them to an axes in a different figure.
# create a figure with one subplot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3,4,5], [1,2,3,4,5], 'r', label='test')
# save it *without* adding a legend
fig.savefig('image.png')
# then create a new image
# adjust the figure size as necessary
figsize = (3, 3)
fig_leg = plt.figure(figsize=figsize)
ax_leg = fig_leg.add_subplot(111)
# add the legend from the previous axes
ax_leg.legend(*ax.get_legend_handles_labels(), loc='center')
# hide the axes frame and the x/y labels
ax_leg.axis('off')
fig_leg.savefig('legend.png')
If for some reason you want to hide only the axes label, you can use:
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
or if, for some weirder reason, you want to hide the axes frame but not the axes labels you can use:
ax.set_frame_on(False)