250

画像を撮って、何らかのプロセスを経て保存する必要があります。Figure を表示すると問題ないように見えますが、Figure を保存した後、保存した画像の周りに空白ができてしまいました。'tight'メソッドのオプションを試しましたがsavefig、うまくいきませんでした。コード:

  import matplotlib.image as mpimg
  import matplotlib.pyplot as plt

  fig = plt.figure(1)
  img = mpimg.imread("image.jpg")
  plt.imshow(img)
  ax=fig.add_subplot(1, 1, 1)

  extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
  plt.savefig('1.png', bbox_inches=extent)

  plt.axis('off') 
  plt.show()

Figure に NetworkX を使用して基本的なグラフを描画し、保存しようとしています。グラフがなくても機能することに気付きましたが、グラフを追加すると、保存された画像の周りに空白ができます。

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_edge(1, 3)
G.add_edge(1, 2)
pos = {1:[100, 120], 2:[200, 300], 3:[50, 75]}

fig = plt.figure(1)
img = mpimg.imread("image.jpg")
plt.imshow(img)
ax=fig.add_subplot(1, 1, 1)

nx.draw(G, pos=pos)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches = extent)

plt.axis('off') 
plt.show()
4

14 に答える 14

283

bbox_inches="tight"で設定することにより、空白のパディングを削除できますsavefig

plt.savefig("test.png",bbox_inches='tight')

引数をbbox_inches文字列として配置する必要があります。おそらくこれが、以前は機能しなかった理由です。


可能な重複:

Matplotlib プロット: 軸、凡例、および空白の削除

matplotlib図のマージンを設定するには?

matplotlib プロットの左右の余白を減らす

于 2012-08-07T13:39:05.087 に答える
17

次の関数には、上記のヨハネスの回答が組み込まれています。複数の軸を使用してテストしましたがplt.figureplt.subplots()うまく機能します。

def save(filepath, fig=None):
    '''Save the current image with no whitespace
    Example filepath: "myfig.png" or r"C:\myfig.pdf" 
    '''
    import matplotlib.pyplot as plt
    if not fig:
        fig = plt.gcf()

    plt.subplots_adjust(0,0,1,1,0,0)
    for ax in fig.axes:
        ax.axis('off')
        ax.margins(0,0)
        ax.xaxis.set_major_locator(plt.NullLocator())
        ax.yaxis.set_major_locator(plt.NullLocator())
    fig.savefig(filepath, pad_inches = 0, bbox_inches='tight')
于 2018-11-28T09:23:50.637 に答える
-4

これは、imshowでプロットされたnumpy配列をファイルに保存するのに役立ちます

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,10))
plt.imshow(img) # your image here
plt.axis("off")
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, 
        hspace = 0, wspace = 0)
plt.savefig("example2.png", box_inches='tight', dpi=100)
plt.show()
于 2018-05-02T01:52:57.027 に答える