Matplotlib获得干净的情节(删除所有装饰)

时间:2016-07-16 12:32:10

标签: python matplotlib

作为参考,同样的问题,但适用于imshow()Matplotlib plots: removing axis, legends and white spaces

在选定答案的嵌入式图像中,由于堆栈溢出页面背景为白色,因此在绘图周围有明显的白色边距并不明显。

@unutbu的以下答案适用于imshow(),但不适用于一般plot()。自版本1.2起,aspect='normal也被弃用。

那么如何将plot()保存为图像,没有任何装饰?

2 个答案:

答案 0 :(得分:2)

ax.set_axis_off(),或等效地,ax.axis('off')切换轴线和标签。要删除更多空格,可以使用

fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)

to remove all whitespace up to the axis' boundaries,请使用

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

这些命令同样适用于ax.imshow(data)ax.plot(data)

例如,

import numpy as np
import matplotlib.pyplot as plt

data = np.arange(1,10).reshape((3, 3))
fig, ax = plt.subplots()
ax.plot(data)
ax.axis('off')
# https://stackoverflow.com/a/4328608/190597 (Joe Kington)
# Save just the portion _inside_ the axis's boundaries
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('/tmp/extent.png', bbox_inches=extent)
fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)

extent.png(504x392):

enter image description here

tight.png(521x414):

enter image description here

答案 1 :(得分:0)

我刚刚了解到,@ unutbu的答案也适用于plot(),如果我们从aspect='normal'指令移除plot()

data = np.arange(1,10).reshape((3, 3))
fig = plt.figure()
fig.set_size_inches(1, 1)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.plot(data)
plt.savefig('test.png')

但是,我仍然想知道所有这些是否真的有必要获得干净的情节? savefig()可以解决这个问题吗?