I try to create a plot in python with matplotlib consisting of two plots and one with a secondary y-axis. The first is a scatter and the second a line plot.
Now, I want to move the legend to somewhere else but whenever I use ax.legend() only the label of the first axis appears but the second vanishes.
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()
The output looks like this with missing labels in the legend for the secondary axis
Without the ax.legend(), the labels for "Value C" and "Value D" are part of the legend.
What is the best way to move all labels at once?

