简体   繁体   中英

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

I have a bar chart. There is 3 columns but the spacing in between on each year is too wide. Is it the add_axes problem? Because I am new of matlibplot. Does anyone know how can I change it?

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()

输出

The width parameter changes the width of bars:

so if you want to arrange them you have to add the index with the width of columns:

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')

Or if you want width to be 0.25 change the middle bar to +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')

For a better organization you can change your code to this:

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 plotting makes life a little easier:

df.plot.bar(width=0.5)

You can adjust width to specify spacing between groups. At 1 , there is no spacing. At 0.5 , the spacing is equal to the the width of the groups, ie, takes up half the total space.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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