0

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)

mozway
  • 194,879
  • 13
  • 39
  • 75
Neek
  • 3
  • 3
  • Here are the same questions as you and the [https://stackoverflow.com/questions/64780251/how-to-annotate-a-seaborn-barplot-with-the-aggregated-value](https://stackoverflow.com/questions/64780251/how-to-annotate-a-seaborn-barplot-with-the-aggregated-value). – r-beginners Mar 26 '22 at 09:41
  • Can't find anything regarding the line plot – Neek Mar 26 '22 at 09:48

1 Answers1

0

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

mozway
  • 194,879
  • 13
  • 39
  • 75
  • the line values should be the % column no? – Neek Mar 26 '22 at 19:57
  • @Neek reading your code again, I think the percentage might not have been computed due to a syntax error (misplaced newline), but this doesn't change the logic. – mozway Mar 26 '22 at 20:42