从 xarray.dataArray 绘图时选择 artists/handles 作为图例

choosing artists/handles for legend when plotting from xarray.dataArray

我正在从 xarray DataArray 绘制一个 facet plot,每个 plot 上有多条线。我想为每个情节都有一个图例,但它应该只包含某些行。我使用 .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'))

我们可以检索 figure-level 个图例条目并过滤它们以获得所需的条目:

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

示例输出:

检索图例条目的代码是从 source code for def add_legend() 中提取的。

另请注意,我已将您的变量 type 更改为 types,因为它隐藏了 Python 函数 type()