图例在具有辅助 y 轴的 matplot 中的位置 (python)

Position of legend in matplot with secondary y-axis (python)

我尝试使用 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”的标签是图例的一部分。

一次移动所有标签的最佳方法是什么?

这种方法(使用您提供的数据):

# 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。这看起来像下面这样: