0

matplotlib の図を pdf に保存する必要があります。結果を表示する代わりに、結果をpdfに保存することを除いて、 Matplotlibのハウツーの指示に従っています。奇妙なことに、pdf キャンバスは canvas resize の影響を受けません。逆に、png への保存は、拡大されたキャンバスで適切に機能します。

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
    bboxes = []
    for label in labels:
        bbox = label.get_window_extent()
        # the figure transform goes from relative coords->pixels and we
        # want the inverse of that
        bboxi = bbox.inverse_transformed(fig.transFigure)
        bboxes.append(bboxi)

    # this is the bbox that bounds all the bboxes, again in relative
    # figure coords
    bbox = mtransforms.Bbox.union(bboxes)
    if fig.subplotpars.left < bbox.width:
        # we need to move it over
        fig.subplots_adjust(left=1.1*bbox.width) # pad a little
        fig.canvas.draw()
    return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.savefig("test.pdf", format="pdf")

PDF画像のスクリーンキャプチャ

アップデート

plt.tight_layout()

は、タイトルと軸の目盛りに対してこれを行いますが、下の図のように、凡例がフレームの外側に配置されている場合は凡例を無視します。凡例を図の右側に配置したことに注意してください。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
p1, = plt.plot(range(10))
p2, = plt.plot(range(10,0,-1))
ax.set_yticks((2,5,7))
plt.labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))
plt.legend([p2, p1], ["line with a loong label", "line with an even longer label, dude!"],\
           loc="center left", bbox_to_anchor=(1, 0.5))
plt.tight_layout()
plt.savefig("test.pdf", format="pdf")
4

2 に答える 2

2

可能なハックはplt.tight_layout()

plt.tight_layout(rect = [0, 0, 0.4, 1])

しかし、それはあまりいいことではありません。私にとってうまくいくのは、引数を使用することbbox_inchesです:

plt.savefig("test.pdf", format="pdf", bbox_inches = 'tight')
于 2013-10-24T09:28:50.733 に答える