以下方法添加了要包含在熔体中的“案例数”列。然后,只使用百分比创建条形图。
钢筋储存在
ax.containers
有两个容器,每个色调值一个容器。
ax.bar_label()
可以获得一个容器和一个标签列表作为输入。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
df_orig = pd.DataFrame({
'years': ['1994-1998', '1999-2003', '2004-2008', '2009-2013', '2013-2017', '2018-2022'],
'Starfish number of cases': [10, 8, 31, 12, 2, 3],
'Starfish percent of wins': [0, 0.25, 0.2258064516, 0.41666666666, 1, 0],
'Jellyfish number of cases': [597, 429, 183, 238, 510, 595],
'Jellyfish percent of wins': [0.3626465661, 0.2738927739, 0.4234972677, 0.4789915966, 0.4058823529, 0.4084033613],
})
df = pd.melt(df_orig, id_vars=['years'],
value_vars=['Starfish number of cases', 'Starfish percent of wins',
'Jellyfish number of cases', 'Jellyfish percent of wins'])
sns.set_theme(style="whitegrid")
# Initialize the matplotlib figure
fig, ax = plt.subplots(figsize=(12, 5))
sns.barplot(x="years", y="value", hue='variable',
hue_order=['Starfish percent of wins', 'Jellyfish percent of wins'], data=df, ax=ax)
for bargroup, variable in zip(ax.containers, ['Starfish number of cases', 'Jellyfish number of cases']):
labels = ['' if val == 0.0 else f'{val:.0f}' for val in df[df['variable'] == variable]['value']]
ax.bar_label(bargroup, labels)
sns.despine()