亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 for 循環 matplotlib 繪制圖例

使用 for 循環 matplotlib 繪制圖例

慕桂英546537 2024-01-27 14:59:36
我正在嘗試使用 for 循環繪制多條線,但我想為每條線創建一個單獨的圖例。每條線代表一個位置,如“拉布拉多?!钡?,但是當我嘗試繪制每條線的圖例時,只有第一個“拉布拉多海”可見如何為每條線制作 matplotlib 圖作為圖例,其中有可定制標簽?這是我到目前為止的代碼:fig,ax=plt.subplots()lines = []for i in [26,27,28,39,30,32,84,86,87,88,96,98,99]:    lines = ax.plot(years, mov_ave(fwf_tot.where(ds.ocean_basins == i).resample(TIME='1AS').sum().sum(dim=('X','Y')),5,'edges'))#plt.title('Total FWF anomalies per ocean basin (moving average)')ax.legend(lines[:13], ['Labrador sea','Hudson strait','Davis strait','Baffin bay', 'Lincoln sea', 'Irish sea and St. George', 'Arctic ocean', 'Barentsz sea', 'Greenland sea',      'North sea', 'Kategat', 'Skagerrak', 'Norwegian sea'],loc='upper left');plt.grid()plt.show()
查看完整描述

1 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

你lines在每個情節之后重新定義。也許你想要:


lines = []


for i in [26,27,28,39,30,32,84,86,87,88,96,98,99]:

    line = ax.plot(years, mov_ave(fwf_tot.where(ds.ocean_basins == i).resample(TIME='1AS').sum().sum(dim=('X','Y')),5,'edges'))

    # add the line to line list

    lines.append(line)


ax.legend(lines, ....)

但是,我認為將標簽傳遞給更干凈ax.plot:


labels = ['Labrador sea','Hudson strait','Davis strait','Baffin bay', 'Lincoln sea', 'Irish sea and St. George', 'Arctic ocean', 'Barentsz sea', 'Greenland sea',

      'North sea', 'Kategat', 'Skagerrak', 'Norwegian sea']


values = [26,27,28,39,30,32,84,86,87,88,96,98,99]

for i,l in zip(values, labels):

    lines = ax.plot(years, mov_ave(fwf_tot.where(ds.ocean_basins == i)

                                          .resample(TIME='1AS').sum()

                                          .sum(dim=('X','Y')),

                                   5,'edges'),

                    label=l)


plt.title('Total FWF anomalies per ocean basin (moving average)')


ax.legend()

plt.grid()

plt.show()


查看完整回答
反對 回復 2024-01-27
  • 1 回答
  • 0 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號