繁体   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()

上面的代码将提供这个堆积条形图。

堆叠图表1

因为 x 轴被指定为相隔 1 周的日期,所以条形之间的距离非常大。

我想更改图表,使条形图彼此相邻,没有空格,如下图所示。

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

堆叠图表2

除了作为 x 轴的数字,我仍然希望将日期保留在图表 1 中。我想知道有没有办法做到这一点? 谢谢!!

造成差异的原因是 matplotlib 会在您传递日期时间时尝试简化 x 轴,因为通常您无法将每个日期都放入 x 刻度中。 它不会为 int 或 string 类型尝试此操作,这就是您的第二个示例看起来正常的原因。

但是我无法弄清楚为什么在这个特定的例子中为什么间距如此奇怪。 我看了这个帖子没有用。

无论如何,还有其他绘图模块倾向于更优雅地处理日期。

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

输出

在此处输入图像描述

暂无
暂无

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

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