簡體   English   中英

如何從 matplotlib 中刪除框架(pyplot.figure 與 matplotlib.figure )(frameon=False 在 matplotlib 中有問題)

[英]How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

要刪除圖中的框架,我寫

frameon=False

pyplot.figure完美配合,但使用matplotlib.Figure它只刪除灰色背景,框架保持不變。 另外,我只希望線條顯示,其余的圖形都是透明的。

使用 pyplot 我可以做我想做的事,我想用 matplotlib 做它出於某種原因我寧願不提擴展我的問題。

ax.axis('off') ,正如喬金頓指出的那樣,將刪除除繪制線以外的所有內容。

對於那些只想移除框架(邊框)並保留標簽、代碼等的人,可以通過訪問軸上的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([])

首先,如果您使用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)

在此處輸入圖片說明

(當然,你看不出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)

在此處輸入圖片說明

在較新版本的 matplotlib 中擺脫丑陋框架的最簡單方法:

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

如果您確實必須始終使用面向對象的方法,請執行以下操作: ax.set_frame_on(False)

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

正如我在此處回答的那樣,您可以通過樣式設置(樣式表或 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

問題

我在使用軸時遇到了類似的問題。 類參數是frameon但 kwarg 是frame_on 軸_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()
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')

我習慣這樣做:

from pylab import *
axes(frameon = 0)
...
show()
plt.axis('off')
plt.savefig(file_path, bbox_inches="tight", pad_inches = 0)

plt.savefig 本身就有這些選項,只需要在設置軸之前關閉

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

應該做的伎倆。

這是另一個解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM