Matplotlib Bar Chart: Space Out Bars

matplotlib bar chart: space out bars

Try replace

plt.bar(range(len(my_dict)), my_dict.values(), align='center')

with

plt.figure(figsize=(20, 3))  # width:20, height:3
plt.bar(range(len(my_dict)), my_dict.values(), align='edge', width=0.3)

Matplotlib bar graph spacing between bars

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

How can I remove space between bars while plotting bar plot using pandas and matplotlib in Python?

The problem is that each point in the x axis is allocating space for 10 different bars. So any size you put, you will always have 9 empty spaces. Instead, you should restructure the df before plotting:

import matplotlib.pyplot as plt

colors = ["royalblue","green","green","red","red","red","royalblue",
"red","red","red","royalblue"]

fig = df.loc[:,"Current level":].T.max(axis=1).plot(kind='bar', bottom=df['Base'], width=1, color=colors)

selected_patches = fig.patches[0], fig.patches[2], fig.patches[4]
plt.legend(selected_patches, ["Base", "Rise", "Fall"], loc = "upper right")

plt.xticks(ticks = np.arange(0, len(df)), labels = df.columns[1:], rotation = 90)

plt.title("My electricity saving plan")

plt.ylabel("kWh consumption")
plt.show()

Result:

Sample Image

Notice that the patches indices also changed, since we don't have all the empty ones anymore.

matplotlib bar chart with labels: space out the bars

There are several options:

  1. Make the figure larger in the horizontal direction.

    fig, ax = plt.subplots(figsize=(10,4))
  2. Make the fontsize smaller

    ax.set_xticklabels(columns, fontsize=8)
  3. Rotate the labels, such that they won't overlap anymore.

    ax.set_xticklabels(columns, rotation=45)

Or, of course any combination of those.

matplotlib how do I reduce the amount of space between bars in a stacked bar chart when x-axis are dates 1-week apart?

The reason for the difference is that matplotlib will try to simplify the x-axis when you pass a datetime, because usually you cannot fit every date in the x-ticks. It doesn't try this for int or string types, which is why your second sample looks normal.

However I'm unable to figure out why in this particular example why the spacing is so odd. I looked at this post to no avail.

In any case, there are other plotting modules that tend to handle dates a little more elegantly.

import pandas as pd
from datetime import datetime
import plotly.express as px
import numpy as np

x=pd.date_range(end=datetime.today(),periods=150,freq='W').tolist()
x_1 = np.random.rand(150)
x_2 = np.random.rand(150)/2

df = pd.DataFrame({
'date':x,
'x_1':x_1,
'x_2':x_2}).melt(id_vars='date')


px.bar(df, x='date', y='value',color='variable')

Output

Sample Image

Setting bar spacing in a matplotlib bar plot

You can change the size of the figure by calling plt.figure(figsize=(x,y)) where x and y are the width and height in inches. That line must be before you call plt.bar.

Alternatively, you can make the label font smaller. You would do that by changing your call to xticks to plt.xticks(range(1, len(labels)+1), labels, size='small').

One more thing to try is to use the plt.xlim() function to manually set the limits of the x axis.



Related Topics



Leave a reply



Submit