Matplotlib savefig在图外带有图例 [英] Matplotlib savefig with a legend outside the plot

查看:361
本文介绍了Matplotlib savefig在图外带有图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读下面的文章时,我设法将图例放在情节之外.

Reading the following article, I managed to put a legend outside plot.

代码:

import matplotlib.pyplot as pyplot

x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]

fig = pyplot.figure()
ax  = fig.add_subplot(111)

box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width*0.8, box.height])

ax.plot(x, y)
leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))
#pyplot.show()

fig.savefig('aaa.png', bbox_inches='tight')

pyplot.show()显示正确的图并在其外面带有图例.但是,当我使用fig.savefig()将其另存为文件时,图例将被截断.

pyplot.show() displays the correct plot with a legend outside it. But when I save it as a file with fig.savefig(), the legend is truncated.

有些谷歌搜索向我显示了一些变通办法,例如将bbox_extra_artists=[leg.legendPatch]bbox_extra_artists=[leg]添加到savefig(),但是都没有.

Some googling shows me workarounds such as adding bbox_extra_artists=[leg.legendPatch] or bbox_extra_artists=[leg] to savefig(), but neither worked.

正确的方法是什么? Matplotlib版本是0.99.3.

What is the correct way to do it? Matplotlib version is 0.99.3.

谢谢.

推荐答案

问题是当您动态绘图时,matplotlib会自动确定边界以适合所有对象. 保存文件时,不会自动完成操作,因此需要指定 图形的大小,然后是轴对象的边界框. 这是更正代码的方法:

The problem is that when you plot dynamically, matplotlib determines the borders automatically to fit all your objects. When you save a file, things are not being done automatically, so you need to specify the size of your figure, and then the bounding box of your axes object. Here is how to correct your code:

import matplotlib.pyplot as pyplot

x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]

fig = pyplot.figure(figsize=(3,3))
ax  = fig.add_subplot(111)

#box = ax.get_position()
#ax.set_position([0.3, 0.4, box.width*0.3, box.height])
# you can set the position manually, with setting left,buttom, witdh, hight of the axis
# object
ax.set_position([0.1,0.1,0.5,0.8])
ax.plot(x, y)
leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))

fig.savefig('aaa.png')

这篇关于Matplotlib savefig在图外带有图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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