簡體   English   中英

如何獲取 matplotlib Axes 實例

[英]How to get a matplotlib Axes instance

我需要使用一些股票數據制作燭台圖。 為此,我想使用 function matplotlib.finance.candlestick() 我需要為這個 function 和“一個 Axes 實例到 plot提供報價”。 我創建了一些示例報價如下:

quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]

不過,我現在還需要一個 Axes 實例,對此我有點迷茫。 我在使用matplotlib.pyplot之前創建了繪圖。 我現在需要對matplotlib.axes做一些事情,但我不確定具體是什么。

有人可以幫助我嗎?

使用gca (“獲取當前軸”)輔助函數:

ax = plt.gca()

例子:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

在此處輸入圖片說明

你可以

fig, ax = plt.subplots()  #create figure and axes
candlestick(ax, quotes, ...)

或者

candlestick(plt.gca(), quotes) #get the axis when calling the function

第一個為您提供了更大的靈活性。 如果燭台是您唯一想要繪制的東西,則第二個要容易得多

每個 Figure 實例都定義了 Axes。 正如提到的其他答案, plt.gca()返回當前的Axes 實例。 要獲取圖上定義的其他 Axes 實例,您可以通過圖的axes屬性查看圖中的 Axes 列表。

import matplotlib.pyplot as plt

plt.plot(range(3))
plt.gcf().axes     # [<Axes: >]


fig, axs = plt.subplots(1, 3)
fig.axes   # [<Axes: >, <Axes: >, <Axes: >]

這將返回一個列表,因此您可以為您想要的特定軸索引它。


如果您使用明顯不返回 Axes 實例的庫創建 plot,這將特別有用。 只要所述庫在后台使用 matplotlib,每個 plot 都有一個 Figure 實例,通過它可以訪問其中的任何 Axes。

例如,如果您使用statsmodels進行 plot 季節性分解,則返回的 object 是一個 matplotlib 圖 object。要更改任何子圖中的某些內容,您可以使用axes屬性。 例如,下面的代碼在分解中的殘差 plot 上使 markersize 變小。

import pandas as pd
from statsmodels.tsa.seasonal import seasonal_decompose
# plot seasonal decomposition
data = pd.Series(range(100), index=pd.date_range('2020', periods=100, freq='D'))
fig = seasonal_decompose(data).plot()

fig.axes  # get Axes list
# [<Axes: >, <Axes: ylabel='Trend'>, <Axes: ylabel='Seasonal'>, <Axes: ylabel='Resid'>]

ax = fig.axes[3]               # last subplot
ax.lines[0].set_markersize(3)  # make marker size smaller on the last subplot

結果

暫無
暫無

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

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