python - 如何将每组条形图居中对齐?我正在尝试创建龙卷风图
问题描述
问题
我的问题与龙卷风包裹无关。
我想了解是否有办法在 Python 中生成龙卷风图表 - 我假设使用 matplotlib 和 seaborn,但任何其他包都可以。
简短的总结是这样的:
- 我有一组条形图
- 说我有 3 个变量
- 对于这三个变量中的每一个,我都在绘制积极变化的影响和消极变化的影响
- 正负条不对齐;我需要它们在中间对齐
龙卷风图是一组位于屏幕中间的条形图;这个概念很简单:
- 你有一个函数可以根据某些输入计算输出
- 您将这些输入中的每一个更改给定百分比,例如 + 和 -10%
- 你计算输出变化的多少
- 您绘制结果,从影响最大的输入到影响最小的输入进行排名
- 例如在下面的(丑陋的)图片中,如果价格上涨 10%,则产出(利润)增加红色条的数量;如果成本增加 10%,则产量减少红色数字
到目前为止我做了什么
使用底部的代码,我可以使用 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,我会调查一下。但是,我不会将我的问题视为完全重复,因为:
- 该问题的输出是如此丑陋以至于它实际上无法使用,而我的并不漂亮但更有用(至少对我而言)。
把它变成不那么难看的东西可能需要大量的工作,并且意味着放弃 seaborn 的便利。
另外,您还可以将我的问题视为与龙卷风图无关的不同问题,因此它们(我敢认为)具有自己的优点:
你如何将宽度参数传递给seaborn?
你如何改变酒吧的对齐方式(间距)?
解决方案
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')
推荐阅读
- entity-framework - 实体框架和 Linq
- python - C中cython纯python模式的使用
- typescript - 我不能替换所有打字稿
- moodle - 将矩阵方程的解代入最大值矩阵乘积
- azure - .NET Core Web API 在部署到 Azure 后无法正常工作
- kubernetes - kubectl 事件从何而来?我如何导出这些?
- julia - 使用 Julia 在 Atom 上使用 LightGraphs 时出错
- python - 无法从主文件访问属性文件中的 Python 字典
- php - 在其他刀片中包含导航栏刀片使“Laravel”中的“CSS”冲突!
- javascript - 一个函数正在改变错误的变量值