'Annotating (adding the values) to figure plot on seaborn (line and bar charts combined)

I have below code that produces the graph but my question here is how to add the values (numbers) to the bars and the markers on the lineplot?

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

flights = sns.load_dataset('flights')
year_flights = flights.groupby('year').sum().reset_index()
year_flights['percentages'] = year_flights['passengers'] / year_flights['passengers'].sum()

print(year_flights)

fig, ax1 = plt.subplots(1, 1, figsize=(12,6))
sns.lineplot(data=year_flights['percentages'], marker='o', ax=ax1)

ax2 = ax1.twinx()
sns.barplot(data=year_flights, x='year', y='passengers', alpha=0.5, 
ax=ax2, color='grey')

plt.show()

I have tried using Matplotlib.pyplot.text() but nothing happens and don't know how to apply it properly (if it can be done this way)



Solution 1:[1]

You can add this block before plt.show():

for pos, row in year_flights.iterrows():
    ax1.annotate(f"{row['percentages']}", (pos, row['percentages']*0.95),
                 color='k', va='top', ha='center')

    ax2.annotate(f"{row['passengers']}", (pos, row['passengers']*1.05),
                 color='k', ha='center')

output:

annotated plot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mozway