如何从matplotlib中删除帧(pyplot.figure与matplotlib.figure)(frameon=False matplotlib中有问题)

2024-04-26 14:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

为了去掉图中的框架,我写了

frameon=False

pyplot.figure一起使用效果很好,但与matplotlib.Figure一起使用只会删除灰色背景,帧会保持不变。另外,我只想让线条显示出来,其余的图形都是透明的。

有了pyplot,我可以做我想做的事情,我想用matplotlib做这件事,原因很长,我宁愿不提扩展我的问题。


Tags: 框架false图形matplotlib原因事情线条figure
3条回答

首先,如果您使用的是savefig,请注意保存时它将覆盖图形的背景色,除非您另有指定(例如fig.savefig('blah.png', transparent=True))。

但是,要删除屏幕上的轴和图形背景,需要将ax.patchfig.patch设置为不可见。

例如

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for item in [fig, ax]:
    item.patch.set_visible(False)

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

(当然,你看不出SO的白色背景有什么不同,但一切都是透明的……)

如果不想显示除直线以外的任何内容,请使用ax.axis('off')关闭轴:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

fig.patch.set_visible(False)
ax.axis('off')

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

不过,在这种情况下,可能需要使轴占据整个图形。如果您手动指定轴的位置,您可以告诉它占据整个图形(或者,您可以使用subplots_adjust,但对于单轴,这更简单)。

import matplotlib.pyplot as plt

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.plot(range(10))

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

enter image description here

ax.axis('off'),正如乔·金顿(Joe Kington)指出的那样,将删除除绘制线之外的所有内容。

对于那些只想移除框架(边框)并保留标签、标记等的人,可以通过访问轴上的spines对象来实现。给定一个axis对象ax,下面应该删除所有四个边上的边框:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

如果从图中去掉xy滴答声:

 ax.get_xaxis().set_ticks([])
 ax.get_yaxis().set_ticks([])

@peeol's excellent answer上构建,还可以通过执行

for spine in plt.gca().spines.values():
    spine.set_visible(False)

举个例子(整个代码示例可以在本文末尾找到),假设您有一个这样的条形图

enter image description here

您可以使用上面的命令删除框架,然后保留x-ytick标签(未显示绘图),或者也可以删除它们

plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

在这种情况下,可以直接标记条形图;最终的绘图可能如下所示(代码如下所示):

enter image description here

以下是生成绘图所需的全部代码:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

xvals = list('ABCDE')
yvals = np.array(range(1, 6))

position = np.arange(len(xvals))

mybars = plt.bar(position, yvals, align='center', linewidth=0)
plt.xticks(position, xvals)

plt.title('My great data')
# plt.show()

# get rid of the frame
for spine in plt.gca().spines.values():
    spine.set_visible(False)

# plt.show()
# remove all the ticks and directly label each bar with respective value
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

# plt.show()

# direct label each bar with Y axis values
for bari in mybars:
    height = bari.get_height()
    plt.gca().text(bari.get_x() + bari.get_width()/2, bari.get_height()-0.2, str(int(height)),
                 ha='center', color='white', fontsize=15)
plt.show()

相关问题 更多 >