如何从matplotlib中删除框架(pyplot.figure vs matplotlib.figure)(frameon =在matplotlib中有问题)

时间:2013-02-16 08:49:38

标签: python matplotlib

要删除图中的帧,我写

frameon=False

pyplot.figure完美配合,但matplotlib.Figure仅删除灰色背景,框架保持不变。此外,我只想要显示线条,而其他所有图形都是透明的。

使用pyplot我可以做我想做的事情,我想用matplotlib来做这件事有一些长期的原因我宁愿不提及扩展我的问题。

12 个答案:

答案 0 :(得分:164)

ax.axis('off'),将像Joe Kington所指出的那样删除除绘制线以外的所有内容。

对于那些只想删除框架(边框),并保留标签,代码等的人,可以通过访问轴上的spines对象来做到这一点。给定轴对象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([])

答案 1 :(得分:127)

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

然而,要移除轴'并且在屏幕上显示背景,您需要将ax.patchfig.patch设置为不可见。

E.g。

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

答案 2 :(得分:43)

@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()

答案 3 :(得分:21)

在较新版本的matplotlib中摆脱最丑陋框架的最简单方法:

from matplotlib.pyplot import plt
plt.box(False)

答案 4 :(得分:5)

我习惯这样做:

from pylab import *
axes(frameon = 0)
...
show()

答案 5 :(得分:5)

要删除图表的框架

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

我希望这行得通

答案 6 :(得分:4)

当我回答here时,您可以通过样式设置(样式表或rcParams)从所有绘图中删除刺:

import matplotlib as mpl

mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False

答案 7 :(得分:2)

问题

我在使用轴时也遇到类似的问题。 class参数为frameon,但kwarg为frame_onaxes_api
>>> plt.gca().set(frameon=False)
AttributeError: Unknown property frameon

解决方案

frame_on

示例

data = range(100)
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(data)
#ax.set(frameon=False)  # Old
ax.set(frame_on=False)  # New
plt.show()

答案 8 :(得分:2)

plt.axis('off')
plt.savefig(file_path, bbox_inches="tight", pad_inches = 0)

plt.savefig本身具有这些选项,只需要先关闭轴

答案 9 :(得分:0)


df = pd.DataFrame({
'client_scripting_ms' : client_scripting_ms,
 'apimlayer' : apimlayer, 'server' : server
}, index = index)

ax = df.plot(kind = 'barh', 
     stacked = True,
     title = "Chart",
     width = 0.20, 
     align='center', 
     figsize=(7,5))

plt.legend(loc='upper right', frameon=True)

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

ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('right')

答案 10 :(得分:0)

plt.box(False)
plt.xticks([])
plt.yticks([])
plt.savefig('fig.png')

应该可以解决问题。

答案 11 :(得分:0)

这是另一种解决方案:

img = io.imread(crt_path)

fig = plt.figure()
fig.set_size_inches(img.shape[1]/img.shape[0], 1, forward=False) # normalize the initial size
ax = plt.Axes(fig, [0., 0., 1., 1.]) # remove the edges
ax.set_axis_off() # remove the axis
fig.add_axes(ax)

ax.imshow(img)

plt.savefig(file_name+'.png', dpi=img.shape[0]) # de-normalize to retrieve the original size