python: label position lineplot() with secondary y-axes

Question:

I have a produce a plot with secondary y-axes and the labels are on top of each other:
enter image description here

The code is the following:

    sns.lineplot(data=incident_cnt["A"], ax=ax,color="#FF4613", marker='o')
    sns.lineplot(data=incident_cnt["B"], ax=ax, color="#80D5FF", marker='o')
    ax2 = ax.twinx()
    sns.lineplot(data=incident_cnt["C"], ax=ax2, color="#00FFAA", marker='o')
    ax.set_xlabel("Date of index event")
    ax.set_ylabel("Patients (no)")
    ax2.set_ylabel("Patients (no) - DIC", color="#00FFAA")
    ax2.set_ylim(0, ax.get_ylim()[1]/10)

is there a way to manually change the position of label C so it does not get on top of A?

Answers:

One way to do this is to remove the individual legends (ax and ax2) and use the figure level legend. Note that you need to add the labels for A, B, C while creating the lineplot. The updated code is below. Note that I have used the seaborn provided flights data as I don’t have your data… should be similar for your data as well. Hope this is what you are looking for

flights = sns.load_dataset("flights")
flights_wide = flights.pivot("year", "month", "passengers")
#flights_wide.columns = flights_wide.columns.get_level_values(0)

fig, ax = plt.subplots()
sns.lineplot(data=flights_wide["May"], ax=ax, color="#FF4613", marker='o', label='A') ## Add label for A
sns.lineplot(data=flights_wide["Jun"], ax=ax, color="#80D5FF", marker='o', label='B') ## Add label for b
ax2 = ax.twinx()
sns.lineplot(data=flights_wide["Jul"], ax=ax2, color="#00FFAA", marker='o', label='C') ## Add label for C
ax.set_xlabel("Date of index event")
ax.set_ylabel("Patients (no)")
ax2.set_ylabel("Patients (no) - DIC", color="#00FFAA")
ax.get_legend().remove() # Remove ax legend
ax2.get_legend().remove() # Remove ax2 legend
fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)

…resulting in plot

enter image description here

Answered By: Redox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.