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)
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()
首先,如果您使用的是
savefig
,请注意保存时它将覆盖图形的背景色,除非您另有指定(例如fig.savefig('blah.png', transparent=True)
)。但是,要删除屏幕上的轴和图形背景,需要将
ax.patch
和fig.patch
设置为不可见。例如
(当然,你看不出SO的白色背景有什么不同,但一切都是透明的……)
如果不想显示除直线以外的任何内容,请使用
ax.axis('off')
关闭轴:不过,在这种情况下,可能需要使轴占据整个图形。如果您手动指定轴的位置,您可以告诉它占据整个图形(或者,您可以使用
subplots_adjust
,但对于单轴,这更简单)。ax.axis('off')
,正如乔·金顿(Joe Kington)指出的那样,将删除除绘制线之外的所有内容。对于那些只想移除框架(边框)并保留标签、标记等的人,可以通过访问轴上的
spines
对象来实现。给定一个axis对象ax
,下面应该删除所有四个边上的边框:如果从图中去掉
x
和y
滴答声:在@peeol's excellent answer上构建,还可以通过执行
举个例子(整个代码示例可以在本文末尾找到),假设您有一个这样的条形图
您可以使用上面的命令删除框架,然后保留
x-
和ytick
标签(未显示绘图),或者也可以删除它们在这种情况下,可以直接标记条形图;最终的绘图可能如下所示(代码如下所示):
以下是生成绘图所需的全部代码:
相关问题 更多 >
编程相关推荐