注释(添加值)到 seaborn 上的图形图(折线图和条形图组合)
Annotating (adding the values) to figure plot on seaborn (line and bar charts combined)
我有以下生成图表的代码,但我的问题是如何将值(数字)添加到线图上的条形图和标记?
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() 但没有任何反应,也不知道如何正确应用它(如果可以这样做的话)
您可以在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')
输出:
我有以下生成图表的代码,但我的问题是如何将值(数字)添加到线图上的条形图和标记?
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() 但没有任何反应,也不知道如何正确应用它(如果可以这样做的话)
您可以在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')
输出: