从具有不同日期的两个DataFrame绘制数据

时间:2020-06-06 20:38:38

标签: python-3.x pandas

我正在尝试从同一图中的两个数据帧绘制数据。问题是我在x轴上使用日历日期,而熊猫显然不喜欢这样。下面的代码显示了我正在尝试做的最小示例。有两个带有与日历日期相关联的数值的数据集。第二数据帧上的数据位于第一数据帧上的数据之后。我想将它们以适当的日期和不同的线条颜色绘制在同一图中。问题在于pandas.DataFrame.plot方法将图表中两个数据框的开始日期合并在一起,从而使可视化效果无用。

import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'date': ['2020-03-10', '2020-03-11', '2020-03-12', '2020-03-13', '2020-03-14', '2020-03-15'],
                    'number': [1, 2, 3, 4, 5, 6]})

df2 = pd.DataFrame({'date': ['2020-03-16', '2020-03-17', '2020-03-18', '2020-03-19'],
                    'number': [7, 6, 5, 4]})


ax = df1.plot(x='date', y='number', label='beginning')
df2.plot(x='date', y='number', label='ending', ax=ax)

plt.show()

创建的图形如下:

enter image description here

有什么办法可以解决这个问题?我还能将日期显示在倾斜的x轴上,以便它们也更清晰吗?

1 个答案:

答案 0 :(得分:2)

您需要使用pd.to_datetime将'date'强制转换为datetime dtype:

import pandas as pd
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'date': ['2020-03-10', '2020-03-11', '2020-03-12', '2020-03-13', '2020-03-14', '2020-03-15'],
                    'number': [1, 2, 3, 4, 5, 6]})

df2 = pd.DataFrame({'date': ['2020-03-16', '2020-03-17', '2020-03-18', '2020-03-19'],
                    'number': [7, 6, 5, 4]})

df1['date'] = pd.to_datetime(df1['date'])
df2['date'] = pd.to_datetime(df2['date'])
ax = df1.plot(x='date', y='number', label='beginning')
df2.plot(x='date', y='number', label='ending', ax=ax)

plt.show()

输出:

enter image description here

相关问题