熊猫Python中共享的x轴

Dav*_*idV 6 python pandas

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

这是在数据框中导入的数据:

         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
Run Code Online (Sandbox Code Playgroud)

我得到的输出是: 在此处输入图片说明

因此,问题是X轴不共享。他们很接近,但没有分享。有什么建议如何解决这个问题?我尝试过sharex=True但Python每次都崩溃。

在此先感谢大家。

最好的问候,大卫

N. *_*uda 6

您可能希望将最终数据帧重新索引为所有数据帧的并集。matplotlib启用时,将最后一个子图的 x 轴作为整个图的轴sharex=True。这应该能让你相处,

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()
Run Code Online (Sandbox Code Playgroud)

产生这个, 在此输入图像描述

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