Pandas Python中的共享x轴

通常我总是在这里得到我的问题的答案,所以这里是一个新问题.我正在进行一些数据分析,我导入不同的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()

以下是在数据框中导入的数据:

         Adj Close
Date                  
2015-12-01  73912.6016
2015-11-02  75638.3984
2015-10-01  79409.0000
2015-09-01  74205.5000
2015-08-03  75210.3984

           Location       CLI
TIME                         
1957-12-01      GBR  98.06755
1958-01-01      GBR  98.09290
1958-02-01      GBR  98.16694
1958-03-01      GBR  98.27734
1958-04-01      GBR  98.40984

我得到的输出是:
《Pandas Python中的共享x轴》

所以,问题是,X轴不是共享的.它们很接近但不共享.有什么建议如何解决这个问题?我尝试使用sharex = True,但Python每次都崩溃了.

先谢谢你们.

最好的问候,大卫

最佳答案 您可能希望将最终数据帧重新索引为所有数据帧的并集.当启用sharex = True时,matplotlib将最后一个子图的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()

产生这个,
《Pandas Python中的共享x轴》

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

点赞