matplotlib 条形图分组条形之间的间距

i2loujxw  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(186)

我有一个条形图,显示了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])

t9aqgxwy

t9aqgxwy1#

您可以将条形图的中心放在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()

相关问题