簡體   English   中英

使用 matplotlib.pyplot 中的 subplots 命令編號圖 windows

[英]Numbering figure windows using the subplots command in matplotlib.pyplot

在 matplotlib.pyplot 中使用命令中的子圖時,有沒有辦法對數字進行編號? 當我想在圖中有一個 plot 時,我可以使用

import matplotlib.pyplot as plt
plt.figure(2)
plot(x,y)

這將創建圖 2 並在其中繪制 plot。 但是,在使用子圖時我不能這樣做

plt.figure(3)
f, ax = plt.subplots(1,2)
ax[0].plot(x,y)

這基本上顯示了一個新的圖 3,然后是另一個圖 4,其中包含子圖。 我想給有子圖的那個編號。

提前致謝。

在調用plt.show()之后,你不能再對這些數字 plot (除非你在一些交互式會話中(?))。 所以讓我們假設你沒有調用 plt.show()。 在這種情況下,您可以通過圖(1)重新激活第一個圖。

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(1, figsize=(10,4))
fig.suptitle('First figure instance')

輸出圖像

現在讓我們使用下面的代碼創建第二個 plot,

plt.figure(2, figsize=(10,5))
plt.subplot(1, 2, 1)
plt.plot(np.random.rand(3,2))
plt.subplot(1, 2, 2)
plt.plot(np.random.rand(3,2))
plt.suptitle('second plot')

sub1 = fig.add_subplot(221)
plt.plot(np.random.rand(3,2))
sub2 = fig.add_subplot(224)
plt.plot(np.random.rand(3,2))
plt.show()

輸出圖像2

使用子圖創建的圖形會自動編號。 您可以通過以下方式檢查:

fig1 = plt.figure(1)
print(fig1.number)
# 1

fig2, axes = plt.subplots(1, 2)
print(fig2.number)
# 2
plt.figure(2)  # this will not create a new figure

使用面向對象的方法,我看不出您想要設置數字編號的原因。

但是,如果您真的想這樣做,請查看pyplot.subplots的文檔,有fig_kw被傳遞給pyplot.figure 在這里,文檔中的第一個參數是num= ,您可以在其中指定圖形編號。 因此,您可以在plt.subplots()中使用此參數:

fig, axes = plt.subplots(1, 2, num=99)
print(fig.number)
# 99

暫無
暫無

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

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