【问题标题】:Matplotlib bar graph spacing between barsMatplotlib 条形图条间距
【发布时间】:2020-12-02 08:19:56
【问题描述】:

我有一个条形图,显示 1996 年至 2020 年的年度数据计数。每年有 2 个酒吧分配给它。我想不出一种方法来增加每组 2 条之间(或每年之间)的间距。我知道我可以更改条形宽度,但这不是我想要的。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import seaborn as sns
sns.set()
sns.set_style("ticks")


record_highs = pd.read_csv('MSY Audubon Record High Comparison 1996-2020.csv')

x= record_highs['Year']
aud = record_highs['AUD']
msy = record_highs['MSY']

plt.figure(figsize = (9,6))

plt.bar(x - 0.25, aud, width = 0.5)
plt.bar(x + 0.25, msy, width = 0.5)
plt.xticks(np.arange(1996, 2021, 1), rotation=45, fontsize=9)

plt.title('Record High Comparison \n May 1996-July 2020')
plt.ylabel('Number of Daily Record Highs by Year')
plt.legend(labels=['Audubon', 'MSY'])
plt.xlim([1995,2021])

【问题讨论】:

    标签: python-3.x pandas numpy matplotlib seaborn


    【解决方案1】:

    您可以将条形的中心放在x - year_width/4x + year_width/4,例如选择year_width0.8

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.ticker as ticker
    import numpy as np
    import seaborn as sns
    sns.set()
    sns.set_style("ticks")
    
    x = np.arange(1996, 2021)
    aud = np.random.randint(0, 26, len(x))
    msy = np.random.randint(0, 26, len(x))
    
    plt.figure(figsize=(9, 6))
    
    year_width = 0.8
    plt.bar(x - year_width / 4, aud, width=year_width / 2, align='center')
    plt.bar(x + year_width / 4, msy, width=year_width / 2, align='center')
    plt.xticks(x, rotation=45, fontsize=9)
    
    plt.title('Record High Comparison \n May 1996-July 2020')
    plt.ylabel('Number of Daily Record Highs by Year')
    plt.legend(labels=['Audubon', 'MSY'])
    plt.xlim([1995, 2021])
    plt.tight_layout()
    plt.show()
    

    【讨论】: