我正在從 xarray DataArray 繪制一個刻面圖,每個圖上有多條線。我想為每個情節都有一個圖例,但它應該只包含某些行。我使用 .legend() 應該給出我想在圖例中擁有的資料,但是當我從 xarray DataArray 繪圖時,我不知道該怎么做。
這里作為示例代碼:
import matplotlib.pyplot as plt
import xarray as xr
import numpy as np
import pandas as pd
data1 = np.random.randn(4, 4,3)
loc= np.linspace(1,3,3)
type = ["a", "b", "c", "d"]
times = pd.date_range("2000-01-01", periods=4)
foo = xr.DataArray(data1, coords=[times, type, loc], dims=["time", "type","loc"])
t=foo.plot.line(x="time", col="loc", linewidth= 5, col_wrap=3)
for i, ax in enumerate(t.axes.flat):
ax.legend(('labelc','labeld'))

在這里,我希望標簽實際適合資料 c 和 d
ax.legend 應該像這樣作業:
ax.legend([line1, line2, line3], ['label1', 'label2', 'label3'])
我已經嘗試過如下方法,但無法正常作業:
for i, ax in enumerate(t.axes.flat):
ax.legend(foo[:,2:,i],('labelc','labeld'))
uj5u.com熱心網友回復:
我們可以檢索圖形級別的圖例條目并過濾它們以獲得所需的條目:
import matplotlib.pyplot as plt
import xarray as xr
import numpy as np
import pandas as pd
data1 = np.random.randn(4, 4, 3)
locs = np.linspace(1, 3, 3)
types = ["a", "b", "c", "d"]
times = pd.date_range("2000-01-01", periods=4)
foo = xr.DataArray(data1, coords=[times, types, locs], dims=["time", "type","loc"])
t=foo.plot.line(x="time", col="loc", linewidth= 5, col_wrap=3)
#define list which entries to show in subplot legends
to_keep = ["b", "d"]
#retrieve global handles and labels
labels = t._hue_var.to_numpy()
handles = t._mappables[-1]
#create a dictionary of labels and handles while filtering unwanted entries
label_dic = {l:h for l, h in zip(labels, handles) if l in to_keep}
#create legend entries as you intended with your code
for ax in t.axes.flat:
ax.legend(label_dic.values(), label_dic.keys(), loc="best")
plt.show()
樣本輸出:

檢索圖例條目的代碼def add_legend()取自.
另請注意,我已將您的變數更改type為,types因為它隱藏了 Python 函式type()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/427097.html
