我的 matplotlib.pyplot 图例被切断 [英] My matplotlib.pyplot legend is being cut off

查看:39
本文介绍了我的 matplotlib.pyplot 图例被切断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用matplotlib创建一个在图例的侧面具有图例的图.我可以看到正在创建绘图,但是图像边界不允许显示整个图例.

I'm attempting to create a plot with a legend to the side of it using matplotlib. I can see that the plot is being created, but the image bounds do not allow the entire legend to be displayed.

lines = []
ax = plt.subplot(111)
for filename in args:
    lines.append(plt.plot(y_axis, x_axis, colors[colorcycle], linestyle='steps-pre', label=filename))
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

这将产生:

推荐答案

正如 Adam 所指出的,您需要在图形的一侧留出空间.如果您想微调所需的空间,您可能需要查看 add_axes 方法.

As pointed by Adam, you need to make space on the side of your graph. If you want to fine tune the needed space, you may want to look at the add_axes method of matplotlib.pyplot.artist.

下面是一个快速的示例:

Below is a rapid example:

import matplotlib.pyplot as plt
import numpy as np

# some data
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

# plot of the data
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])
ax.plot(x, y1,'-k', lw=2, label='black sin(x)')
ax.plot(x, y2,'-r', lw=2, label='red cos(x)')
ax.set_xlabel('x', size=22)
ax.set_ylabel('y', size=22)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

以及生成的图像:

这篇关于我的 matplotlib.pyplot 图例被切断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆