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)
CodePudding user response:
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: