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

查看:47
本文介绍了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') 比更改每个轴和分界线.然而,它仍然在边界周围留下空白.将 bbox_inches='tight' 添加到 savefig 命令几乎可以让您达到目标,您可以在下面的示例中看到,左边的空白要小得多,但仍然存在.

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天全站免登陆