Pandas Python中的共享x轴

2024-10-01 13:44:37 发布

您现在位置:Python中文网/ 问答频道 /正文

通常我在这里总能得到我问题的答案,所以这里有一个新的答案。我正在做一些数据分析,在那里我导入不同的csv文件,设置索引,然后我试图绘制它。在

这是密码。请注意,我使用obdobje-obdobje,因为索引来自不同的文件,但格式相同:

#to start plotting
fig, axes = plt.subplots(nrows=2, ncols=1)

#first dataframe
df1_D1[obdobje:].plot(ax=axes[0], linewidth=2, color='b', linestyle='solid')

#second dataframe
df2_D1[obdobje:].plot(ax=axes[0], linewidth=2, color='b',linestyle='dashed')

#third data frame
df_index[:-obdobje].plot(ax=axes[1])

plt.show()

以下是数据帧中导入的数据:

^{pr2}$

我得到的输出是: enter image description here

所以,问题是,X轴是不共享的。他们关系密切,但不是共享的。有什么建议可以解决这个问题吗?我尝试使用sharex=True,但Python每次都崩溃。在

提前谢谢各位。在

谨致问候,大卫


Tags: 文件csv数据答案dataframeplotpltax
1条回答
网友
1楼 · 发布于 2024-10-01 13:44:37

您可能需要将最终数据帧重新索引为所有数据帧的联合。matplotlib在启用sharex=True时,将最后一个子图的x轴作为整个绘图的轴。这会让你相处得很好

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2,
                         ncols=1,
                         sharex=True)

df1 = pd.DataFrame(
    data = np.random.rand(25, 1),
    index=pd.date_range('2015-05-05', periods=25),
    columns=['DF1']
)

df2 = pd.DataFrame(
    data = np.random.rand(25, 1),
    index=pd.date_range('2015-04-10', periods=25),
    columns=['DF2']
)

df3 = pd.DataFrame(
    data = np.random.rand(50, 1),
    index=pd.date_range('2015-03-20', periods=50),
    columns=['DF3']
)

df3 = df3.reindex(index=df3.index.union(df2.index).union(df1.index))

df1.plot(ax=axes[0], linewidth=2, color='b', linestyle='solid')
df2.plot(ax=axes[0], linewidth=2, color='b', linestyle='dashed')
df3.plot(ax=axes[1])

plt.show()

产生这个, enter image description here

如您所见,轴现在已对齐。在

相关问题 更多 >