bayouwxman
bayouwxman

Reputation: 89

Bar graph spacing between grouped bars

I have a bar graph displaying annual counts of data from 1996-2020. Each year has 2 bars assigned to it. I can't figure out a way to increase the spacing between each group of 2 bars (or between each year). I know I can change the bar width, but that's not what I'm looking for.

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

Record Highs Bar Graph

Upvotes: 0

Views: 4893

Answers (1)

JohanC
JohanC

Reputation: 80319

You could put the center of the bars at x - year_width/4 and x + year_width/4, e.g. choosing year_width to be 0.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()

example plot

Upvotes: 1

Related Questions