您可以使用seaborn 绘制没有误差线的条形图。然后使用matplotlib的errorbar
添加误差线。下面的代码假设'Group'
列包含两个不同的值:
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
x = pd.DataFrame([
['Group 1', 0.5, 0.05],
['Group 2', 0.6, 0.07],
], columns=['Group', 'Mean', 'SD'])
ax = sns.barplot(data=x, x='Group', y='Mean', color='dodgerblue')
ax.errorbar(data=x, x='Group', y='Mean', yerr='SD', ls='', lw=3, color='black')
plt.show()
这是嵌套栏的尝试。首先绘制误差条以获得其标准位置并提取 x 坐标。然后,这些条将被删除并以新位置重新创建。我不确定它是否在所有情况下都有效。
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
x = pd.DataFrame([
['Group 1', 'A', 0.4, 0.08],
['Group 1', 'B', 0.5, 0.05],
['Group 1', 'C', 0.5, 0.02],
['Group 2', 'A', 0.6, 0.07],
['Group 2', 'B', 0.7, 0.09],
['Group 2', 'C', 0.7, 0.02],
['Group 3', 'A', 0.6, 0.07],
['Group 3', 'B', 0.2, 0.09],
['Group 3', 'C', 0.4, 0.11],
], columns=['Group', 'Subgroup', 'Mean', 'SD'])
num_hues = len(np.unique(x['Subgroup']))
ax = sns.barplot(data=x, x='Group', y='Mean', hue='Subgroup')
for (hue, df_hue), dogde_dist in zip(x.groupby('Subgroup'), np.linspace(-0.4, 0.4, 2 * num_hues + 1)[1::2]):
bars = ax.errorbar(data=df_hue, x='Group', y='Mean', yerr='SD', ls='', lw=3, color='black')
xys = bars.lines[0].get_xydata()
bars.remove()
ax.errorbar(data=df_hue, x=xys[:, 0] + dogde_dist, y='Mean', yerr='SD', ls='', lw=3, color='black')
plt.show()