【问题标题】:Seaborn barplot does not show columns side by sideSeaborn barplot 不并排显示列
【发布时间】:2019-11-29 19:51:45
【问题描述】:

在下图中,同一年份的阈值条不是并排的:

我想要如下图:

my_df = pd.DataFrame(data={'Year': \['2017','2018','2019','2019','2019','2019','2020','2020'\],
          'Threshold':\[96, 91, 20.59, 47.37, 78.12, 10.00, 15.00 ,91\],
          'Fee' : \["No","No", "20%", "20%", "5%", "20%", "20%", "No"\]})

    palette={"No": "g","20%": "y", "5%": "r"}

    fig,ax = plt.subplots()
    fig.set_size_inches(10,8)

    g = sns.barplot(x=my_df.index, y="Threshold",hue = 'Fee', palette = palette, data=my_df, ci=None)
    g.set(xticklabels=my_df\['Year'\])

    for p in ax.patches: 
        ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2, p.get_height()),
                    ha='center', va='center', fontsize=11, color='black', xytext=(0, 10), 
                    textcoords='offset points',fontweight='bold')][3]][3]

【问题讨论】:

  • 如果你使用g = sns.barplot(x='Year', y="Threshold",hue = 'Fee', palette = palette, data=my_df, ci=None),这会让你更接近你想要的输出。但是,您必须记住,seaborn 会保留每种色调的相对位置,因此如果只有一个色调值,条形将与年份偏移,并且给定年份/色调组合的各种值将被聚合在一起。
  • 是的,这就是重点。我不想要每年/色调的汇总值。我想要一个类似于上面显示的第二个图的图。在 seaborn 或其他数据可视化库中是否有其他方法可以做到这一点?

标签: python alignment bar-chart seaborn axis-labels


【解决方案1】:

当你偏离 seaborn 设计的那种情节时,你最好直接依赖 matplotlib 而不是试图让 seaborn 屈服于你的意愿

my_df = pd.DataFrame(data={'Year': ['2017','2018','2019','2019','2019','2019','2020','2020'],
          'Threshold':[96, 91, 20.59, 47.37, 78.12, 10.00, 15.00 ,91],
          'Fee' : ["No","No", "20%", "20%", "5%", "20%", "20%", "No"]})
palette={"No": "g","20%": "y", "5%": "r"}

temp_df = my_df.sort_values(by=['Year','Fee'])

years = temp_df['Year'].unique()
max_bars = temp_df.groupby('Year').size().max()
width = .8/max_bars

fig, ax = plt.subplots()
for i,(year,yearly_df) in enumerate(temp_df.groupby('Year')):
    N_bars = len(yearly_df)
    offsets = np.linspace(0, (N_bars-1)*width, N_bars)
    offsets -= offsets.mean()
    a = ax.bar(i+offsets, yearly_df['Threshold'], width=width, color=yearly_df['Fee'].replace(palette))
ax.set_xticks(np.arange(len(years)))
ax.set_xticklabels(years)

for p in ax.patches: 
    ax.annotate("%.2f" % p.get_height(), (p.get_x() + p.get_width() / 2, p.get_height()),
                    ha='center', va='center', fontsize=11, color='black', xytext=(0, 10), 
                    textcoords='offset points',fontweight='bold')

【讨论】:

  • 感谢 Diziet Asahi 分享了这种绘制我的数据框的新方法。这就是我想要的解决方案。
猜你喜欢
  • 2017-08-30
  • 1970-01-01
  • 2020-02-28
  • 2017-11-11
  • 2019-12-02
  • 1970-01-01
  • 2021-03-04
  • 2020-11-05
  • 2019-04-05
相关资源
最近更新 更多