如何从图形中删除框架
- 2025-04-15 09:18:00
- admin 原创
- 27
问题描述:
为了删除图中的框架,我写道
frameon=False
与 配合使用效果很好pyplot.figure
,但使用matplotlib.Figure
只会移除灰色背景,边框会保留。另外,我只希望显示线条,其余部分保持透明。
使用 pyplot 我可以做我想做的事,但我想用 matplotlib 来做,出于某些很长的原因,我宁愿不提及以扩展我的问题。
解决方案 1:
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)
并且,如果从图中删除x
和勾选:y
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
解决方案 2:
首先,如果您使用savefig
,请注意,除非您另有指定(例如),否则它将在保存时覆盖图形的背景颜色fig.savefig('blah.png', transparent=True)
。
但是,要删除屏幕上的轴和图形的背景,您需要将两者都设置ax.patch
为fig.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)
(当然,在 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)
不过,在这种情况下,您可能希望让坐标轴占据整个图形。如果您手动指定坐标轴的位置,则可以让它占据整个图形(或者,您可以使用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)
解决方案 3:
摆脱新版本 matplotlib 中丑陋框架的最简单方法:
import matplotlib.pyplot as plt
plt.box(False)
如果您确实必须始终使用面向对象的方法,那么请执行以下操作:ax.set_frame_on(False)
。
解决方案 4:
基于@peeol 的出色回答,您还可以通过执行以下操作来删除框架
for spine in plt.gca().spines.values():
spine.set_visible(False)
举个例子(完整的代码示例可以在本文末尾找到),假设你有一个这样的条形图,
您可以使用上面的命令删除框架,然后保留x-
和ytick
标签(未显示图表)或删除它们
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
在这种情况下,可以直接标记条形;最终的图可能看起来像这样(代码可以在下面找到):
以下是生成图表所需的全部代码:
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()
解决方案 5:
正如我在这里回答的那样,您可以通过样式设置(样式表或 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
解决方案 6:
问题
我在使用axes时也遇到了类似的问题。类参数是 ,但frameon
kwarg是frame_on
。axes_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()
解决方案 7:
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')
解决方案 8:
plt.axis('off')
plt.savefig(file_path, bbox_inches="tight", pad_inches = 0)
plt.savefig 本身就有这些选项,只需在之前关闭轴即可
解决方案 9:
我曾经这样做过:
from pylab import *
axes(frameon = 0)
...
show()
解决方案 10:
plt.box(False)
plt.xticks([])
plt.yticks([])
plt.savefig('fig.png')
应该可以解决问题。
解决方案 11:
这是另一个解决方案:
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
解决方案 12:
对我有用的解决方案(matplotlib 3.8.2
)是在创建期间使用参数 frameonplt.figure
来删除图像周围的白框(正如问题所论证的那样应该有效),可以看到下面的最小可重现代码:
import matplotlib.pyplot as plt
import requests
from PIL import Image
img_url = # SOME_URL_FOR_IMAGE
raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
plt.figure(figsize=(20,20), frameon=False) # frameon=False solved it
ax = plt.gca()
ax.imshow(raw_image)
plt.axis('off')
plt.show()
扫码咨询,免费领取项目管理大礼包!