Matplotlib图:删除轴,图例和空白 [英] Matplotlib plots: removing axis, legends and white spaces

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

问题描述

我是Python和Matplotlib的新手,我想简单地将色彩映射表应用于图像并写入结果图像,而无需使用轴,标签,标题或通常由matplotlib自动添加的任何内容.这是我所做的:

I'm new to Python and Matplotlib, I would like to simply apply colormap to an image and write the resulting image, without using axes, labels, titles or anything usually automatically added by matplotlib. Here is what I did:

def make_image(inputname,outputname):
    data = mpimg.imread(inputname)[:,:,0]
    fig = plt.imshow(data)
    fig.set_cmap('hot')
    fig.axes.get_xaxis().set_visible(False)
    fig.axes.get_yaxis().set_visible(False)
    plt.savefig(outputname)

它成功删除了图形的轴,但是保存的图形在实际图像周围显示了白色填充和边框. 如何删除它们(至少是白色填充)?谢谢

It successfully removes the axis of the figure, but the figure saved presents a white padding and a frame around the actual image. How can I remove them (at least the white padding)? Thanks

推荐答案

我认为与单独更改每个轴和边框相比,命令axis('off')可以更简洁地解决一个问题.但是,它仍然在边框周围留有空白区域.在savefig命令中添加bbox_inches='tight'几乎可以到达那里,在下面的示例中您可以看到剩余的空白空间小得多,但仍然存在.

I think that the command axis('off') takes care of one of the problems more succinctly than changing each axis and the border separately. It still leaves the white space around the border however. Adding bbox_inches='tight' to the savefig command almost gets you there, you can see in the example below that the white space left is much smaller, but still present.

请注意,较新版本的matplotlib可能需要bbox_inches=0而不是字符串'tight'(通过@episodeyang和@kadrach)

Note that newer versions of matplotlib may require bbox_inches=0 instead of the string 'tight' (via @episodeyang and @kadrach)

from numpy import random
import matplotlib.pyplot as plt

data = random.random((5,5))
img = plt.imshow(data, interpolation='nearest')
img.set_cmap('hot')
plt.axis('off')
plt.savefig("test.png", bbox_inches='tight')

这篇关于Matplotlib图:删除轴,图例和空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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