我有以下生成圖表的代碼,但我的問題是如何將值(數字)添加到線條圖上的條和標記?
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()
我曾嘗試使用 Matplotlib.pyplot.text() 但沒有任何反應,也不知道如何正確應用它(如果可以這樣做的話)
uj5u.com熱心網友回復:
您可以在之前添加此塊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')
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451520.html
標籤:Python matplotlib 海运
