繁体   English   中英

如何调整条形图的图形间距。 Matplotlib

[英]How can I adjust the graph spacing of a bar chart. Matplotlib

我有一个条形图。 有 3 列,但每年之间的间距太宽。 是 add_axes 问题吗? 因为我是 matlibplot 的新手。 有谁知道我该如何改变它?

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import style
style.use('ggplot')

dict_ = {'date': [pd.Timestamp('20150720'),pd.Timestamp('20160720'),pd.Timestamp('20170720'),pd.Timestamp('20180720'),pd.Timestamp('20190720'),pd.Timestamp('20200720')],
            'BKNG': [15.22, 6.36, 5.05, 5, 9.3641, -3],
            'MCD' : [25.22, 11.36, 7.05, 9, 8.3641, -6],
            'YUM' : [52.22, 21.36, 25.05, 26, 21.3641, -10]
    
}

df = pd.DataFrame(dict_)
df['date'] = df['date'].dt.year
df.set_index('date',inplace=True)

fig = plt.figure(figsize=(10,8))
ax = fig.add_axes([0,0,1,1])

ax.bar(df.index+0.00, df['BKNG'], color = 'b', width = 0.10, label='BKNG')
ax.bar(df.index+0.20, df['MCD'], color = 'g', width = 0.10, label='MCD')
ax.bar(df.index+0.30, df['YUM'], color = 'r', width = 0.10, label='YUM')

plt.title('ROE')
plt.xlabel('date')
plt.ylabel('value')

plt.legend()
plt.show()

输出

width 参数改变条的宽度:

所以如果你想排列它们,你必须添加具有列宽的索引:

ax.bar(df.index+0.00, df['BKNG'], color = 'b', width = 0.2, label='BKNG')
ax.bar(df.index+0.20, df['MCD'], color = 'g', width = 0.2, label='MCD')
ax.bar(df.index+0.40, df['YUM'], color = 'r', width = 0.2, label='YUM')

或者,如果您希望宽度为 0.25,请将中间栏更改为 +0.25

ax.bar(df.index+0.00, df['BKNG'], color = 'b', width = 0.25, label='BKNG')
ax.bar(df.index+0.25, df['MCD'], color = 'g', width = 0.25, label='MCD')
ax.bar(df.index+0.50, df['YUM'], color = 'r', width = 0.25, label='YUM')

为了更好的组织,您可以将代码更改为:

i=0
width = 0.25
gap = .02
cols = ['BKNG','MCD','YUM']
colors= ['b','g','r']
for col in cols:
    ax.bar(df.index+(i*(width+gap)), df[col], color = colors[i], width = width, label=col)
    i+=1

Pandas 绘图让生活更轻松:

df.plot.bar(width=0.5)

您可以调整width以指定组之间的间距。 1处,没有间距。 0.5时,间距等于组的宽度,即占总空间的一半。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM