首页 > 解决方案 > 如何将每组条形图居中对齐?我正在尝试创建龙卷风图

问题描述

问题

我的问题与龙卷风包裹无关。

我想了解是否有办法在 Python 中生成龙卷风图表 - 我假设使用 matplotlib 和 seaborn,但任何其他包都可以。

简短的总结是这样的

龙卷风图是一组位于屏幕中间的条形图;这个概念很简单:

在此处输入图像描述

到目前为止我做了什么

使用底部的代码,我可以使用 seaborn 制作条形图;我用 catplot 和 barplot 得到相同的输出;然而:

如何移动条以便每组橙色和蓝色条对齐?

它必须类似于设置从一个条到另一个条的负间距,但我不能将宽度参数传递给 seaborn 函数,或者我得到

TypeError: barh() got multiple values for argument 'width'

我的输出是:

在此处输入图像描述

我的代码:

**

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='darkgrid')

# creating a dataframe
df = pd.DataFrame()
df['input'] = ['x','y','z']
df['+']=[100,-50,10]
df['-']=[-80,60,-10]

#now stacking it
df2 = pd.melt(df, id_vars ='input', var_name='type of change', value_name='change in the output' )
print(df2)

fig,ax = plt.subplots(1,2)

sns.catplot(y='input', x='change in the output', hue='type of change',data=df2, kind='bar', \
            orient='h', ax = ax[0])

sns.barplot(y='input', x='change in the output', hue='type of change',data=df2, \
            orient='h', ax= ax[1], width =0.4)

编辑:评论指出了这个matplotlib答案。我不熟悉broken_barh,我会调查一下。但是,我不会将我的问题视为完全重复,因为:

标签: pythonmatplotlibbar-chartseaborn

解决方案


This is one way of doing it. The idea is to first split the DataFrame using groupby, finding the unique values of types (+ and - in your case) and then plotting them on one common axis object ax. For a horizontal bar chart, you want to supply the height argument to control the width of the bars.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style='darkgrid')

# creating a dataframe
df = pd.DataFrame()
df['input'] = ['x','y','z']
df['+']=[100,-50,10]
df['-']=[-80,60,-10]

#now stacking it
df2 = pd.melt(df, id_vars ='input', var_name='type of change', value_name='change in the output' )

fig, ax = plt.subplots()
for typ, df in zip(df2['type of change'].unique(),df2.groupby('type of change')):
    ax.barh(df[1]['input'], df[1]['change in the output'], height=0.3, label=typ)
ax.legend(title = 'type of change')  

enter image description here


推荐阅读