在matplotlib

时间:2017-12-08 22:54:11

标签: python pandas matplotlib

我正在绘制一个来自pandas数据帧的叠加折线图。在两天的过程中不定期地收集数据。在下图中,您可以看到相等间隔之间的时间变化(等间隔间隔约7小时至约36小时)。我不希望这种情况发生,我希望图形上的点被适当地拉伸和挤压,使得时间与x轴线性地成比例。我怎么能这样做?

数据内容如下:

df = pd.read_csv("filepath", index_col=0)
df = df.T 

上面,我不得不将大熊猫堆叠线图的数据帧转换为我想要的工作。情节如下:

plot = df.plot.area(rot=90)
plot.axhline(y=2450, color="black")

enter image description here

作为对ImportanceOfBeingErnest的回应,这是一个最小,完整且可验证的例子:

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

dateTimeIndex = ["04.12.17 23:03", "05.12.17 00:09", "05.12.17 21:44", "05.12.17 22:34", "08.12.17 16:23"]

d = {'one' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'two' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'three' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex)}

df = pd.DataFrame(d)

plot = df.plot.area(rot=90)

以下是数据框的外观(随机值会有所不同):

                one       three     two
04.12.17 23:03  0.472832  0.283329  0.739657
05.12.17 00:09  3.166099  1.065015  0.561079
05.12.17 21:44  0.209190  0.674236  0.143453
05.12.17 22:34  1.275056  0.764328  0.650507
08.12.17 16:23  0.764038  0.265599  0.342435

并制作了情节:

Minimal, verifiable example

正如您所知,dateTimeIndex条目相当随机,但它们在x轴上的间距相等。我不介意刻度标记是否与数据点重合。我只想要时间线性扩展。如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

上面发生的事情是熊猫只是将字符串用作x-ticks。您需要将dateTimeIndex设为日期时间对象:

dateTimeIndex = pd.to_datetime( ["04.12.17 23:03", "05.12.17 00:09", 
                "05.12.17 21:44", "05.12.17 22:34", "08.12.17 16:23"])

d = {'one' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'two' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'three' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex)}

df = pd.DataFrame(d)    
plot = df.plot.area(rot=90)
相关问题