首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除已经使用set_axis_off、bbox_inches=tight和pad_inches=0的matplotlib行图中的填充?

删除已经使用set_axis_off、bbox_inches=tight和pad_inches=0的matplotlib行图中的填充?
EN

Stack Overflow用户
提问于 2018-01-05 16:09:26
回答 1查看 318关注 0票数 0

我试图将一些数据绘制成给定大小的图像(用作覆盖)。然而,尽管调用了set_axis_off()并在savefig上设置了bbox_inches="tight"pad_inches=0 (就像其他问题中所建议的那样),我仍然得到了填充,并且比图大小更大的图像大小应该会导致填充。

下面是代码( PIL依赖关系是为了便于使用,但可以通过删除最后一行来删除):

代码语言:javascript
复制
from PIL import Image
import matplotlib.pyplot as plt

def plot_box(data, size, filename="plot.png"):
    """Plot the data in an image whose dimensions are size x size pixels"""
    fig = plt.figure(figsize=(size/100,size/100), dpi=100)
    ax = fig.add_axes((0,0,1,1))
    ax.set_axis_off()
    ax.plot(data)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.savefig(filename, bbox_inches="tight", pad_inches=0, dpi='figure', transparent=True)
    plt.close()
    return Image.open(filename)

但是,无论我指定的大小如何,图像在两个方向上总是宽6或7个像素:

代码语言:javascript
复制
>> data = [i**2 for i in range(-100, 101)]
>> plot_box(data, 50)
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=57x57 at 0xED3CB38>
>> plot_box(data, 100)
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=106x106 at 0xF208908>
>> plot_box(data, 1)
<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=8x8 at 0x53D2748>

有什么想法吗?

更新

这是plot_box(data, 100)生成的图像。如您所见,由于填充(106x106而不是100x100),它看起来比预期的要大得多。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-08 12:02:51

bbox_inches="tight"调用中删除savefig。然后,您也不需要pad_inches

代码语言:javascript
复制
plt.savefig(filename, dpi='figure', transparent=True)

这将导致100×100像素的图像。

如果您也不想在轴内有任何边距,将其设置为0,

代码语言:javascript
复制
ax.margins(0)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48117247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档