简体   繁体   English

matplotlib当x轴相隔1周时,如何减少堆积条形图中条形之间的空间量?

[英]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堆叠图表1

Because the x-axis are specified as dates with 1 week apart, the distance between bars are very large.因为 x 轴被指定为相隔 1 周的日期,所以条形之间的距离非常大。

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堆叠图表2

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?除了作为 x 轴的数字,我仍然希望将日期保留在图表 1 中。我想知道有没有办法做到这一点? 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.造成差异的原因是 matplotlib 会在您传递日期时间时尝试简化 x 轴,因为通常您无法将每个日期都放入 x 刻度中。 It doesn't try this for int or string types, which is why your second sample looks normal.它不会为 int 或 string 类型尝试此操作,这就是您的第二个示例看起来正常的原因。

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输出

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM