我嘗試使用 matplotlib 在 python 中創建一個圖,該圖由兩個圖和一個具有輔助 y 軸的圖組成。第一個是散點圖,第二個是線圖。現在,我想將圖例移動到其他地方,但每當我使用ax.legend()第一個軸的標簽時,就會出現第二個軸的標簽。
import pandas as pd
# the data:
data = pd.DataFrame(
{'Date': {0: '2021-01-01 18:00:00', 1: '2021-01-02 20:00:00', 2: '2021-01-03 19:00:00', 3: '2021-01-04 17:00:00', 4: '2021-01-05 18:00:00', 5: '2021-01-06 18:00:00', 6: '2021-01-07 21:00:00', 7: '2021-01-08 16:00:00'},
'Value A': {0: 107.6, 1: 86.0, 2: 17.3, 3: 56.8, 4: 30.0, 5: 78.3, 6: 110.1, 7: 59.0},
'Value B': {0: 17.7, 1: 14.1, 2: 77.4, 3: 4.9, 4: 44.4, 5: 28.3, 6: 22.9, 7: 83.2},
'Value C': {0: 0.0, 1: 0.5, 2: 0.3, 3: 0.6, 4: 0.9, 5: np.nan, 6: 0.1, 7: 0.8},
'Value D': {0: 0.5, 1: 0.7, 2: 0.1, 3: 0.5, 4: 0.4, 5: 0.8, 6: 0.8, 7: 0.8},
'Flag': {0: 1, 1: np.nan, 2: np.nan, 3: np.nan, 4: np.nan, 5: np.nan, 6: 1, 7: np.nan}})
data["Date"] = pd.to_datetime(data["Date"])
# plot the flagged points as dots
data_flag = data[data["Flag"] == True]
ax = data_flag.plot.scatter(x="Date",
y="Value A",
c="black",
label="Outlier")
# plot the series as lines
ax = data.plot(x="Date",
y=["Value A",
"Value B",
"Value C",
"Value D"
],
secondary_y=["Value C", "Value D"],
ax=ax
)
ax.legend(bbox_to_anchor=(1.1, 1.05))
plt.show()
輸出看起來像這樣,在輔助軸的圖例中缺少標簽

如果沒有ax.legend(),“值 C”和“值 D”的標簽是圖例的一部分。
一次移動所有標簽的最佳方法是什么?
uj5u.com熱心網友回復:
這種方法(使用您提供的資料):
# plot the flagged points as dots
data_flag = data[data["Flag"] == True]
ax = data_flag.plot.scatter(x="Date",
y="Value A",
c="black",
label="Outlier")
# plot the series as lines
ax = data.plot(x="Date",
y=["Value A",
"Value B",
],
secondary_y=False,
ax=ax
)
ax2 = data.plot(x="Date",
y=["Value C",
"Value D"
],
secondary_y=True,
ax=ax
)
ax.legend(bbox_to_anchor=(1.1, 1.1), loc="upper left")
ax.set_ylabel("Value A, Value B")
ax2.legend(bbox_to_anchor=(1.1, 0.85), loc="upper left")
ax2.set_ylabel("Value C, Value D")
plt.show()
生成了三個圖,一個用于標記的例外值,一個用于Value A, Value B,最后一個帶有輔助 y 軸的Value C, Value D. 如下所示:

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/406728.html
標籤:
