简体   繁体   中英

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

import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
x=pd.date_range(end=datetime.today(),periods=150,freq='W').to_pydatetime().tolist()
x_1 = np.random.rand(150)
x_2 = np.random.rand(150)/2
fig = plt.figure(figsize=(10,6),dpi=100)
ax=fig.add_subplot(111)
ax.bar(x,x_1,label='x_1')
ax.bar(x,x_2,label='x_2',bottom=x_1)
plt.legend()
plt.show()

The above code will provide this stacked bar chart.

stacked_chart1

Because the x-axis are specified as dates with 1 week apart, the distance between bars are very large.

I would like to change the chart so that the bars are next to each other with no space like the picture below.

x=np.arange(150)
x_1 = np.random.rand(150)
x_2 = np.random.rand(150)/2
fig = plt.figure(figsize=(10,6),dpi=100)
ax=fig.add_subplot(111)
ax.bar(x,x_1,label='x_1')
ax.bar(x,x_2,label='x_2',bottom=x_1)
plt.legend()
plt.show()

stacked_chart2

Except numbers as x-axis, I would still want to keep the dates in chart 1. I am wondering is there a way to do that? Thanks!!

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

在此处输入图像描述

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