Matplotlib时间轴 [英] Matplotlib timelines

查看:420
本文介绍了Matplotlib时间轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个带有一串时间轴的python DataFrame,并将它们绘制在一个图中. DataFrame索引是时间戳,这里有一个特定的列,我们称为序列",其中包含诸如"A"和"B"之类的字符串.因此,DataFrame看起来像这样:

I'm looking to take a python DataFrame with a bunch of timelines in it and plot these in a single figure. The DataFrame indices are Timestamps and there's a specific column, we'll call "sequence", that contains strings like "A" and "B". So the DataFrame looks something like this:

+--------------------------+---+
| 2014-07-01 00:01:00.0000 | A |
+--------------------------+---+
| 2014-07-01 00:02:00.0000 | B |
+--------------------------+---+
| 2014-07-01 00:04:00.0000 | A |
+--------------------------+---+
| 2014-07-01 00:08:00.0000 | A |
+--------------------------+---+
| 2014-07-01 00:08:00.0000 | B |
+--------------------------+---+
| 2014-07-01 00:10:00.0000 | B |
+--------------------------+---+
| 2014-07-01 00:11:00.0000 | B |
+--------------------------+---+

我正在寻找类似这样的情节:

I'm looking for a plot something like this:

B |  *     * **
A | *  *   *
  +------------
    Timestamp

推荐答案

我只是使用字典将每个类别映射到y值.

I would just map each category to a y-value using a dictionary.

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

categories = list('ABCD')

# map categories to y-values
cat_dict = dict(zip(categories, range(1, len(categories)+1)))

# map y-values to categories
val_dict = dict(zip(range(1, len(categories)+1), categories))

# setup the dataframe
dates = pandas.DatetimeIndex(freq='20T', start='2012-05-05 13:00', end='2012-05-05 18:59')
values = [random.choice(categories) for _ in range(len(dates))]
df = pandas.DataFrame(data=values, index=dates, columns=['category'])

# determing the y-values from categories
df['plotval'] = df['category'].apply(cat_dict.get)

# make the plot
fig, ax = plt.subplots()
df['plotval'].plot(ax=ax, style='ks')
ax.margins(0.2)

# format y-ticks look up the categories
ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, pos: val_dict.get(x)))

然后我得到:

请注意,由于您可能已经有了一个数据框,因此可以像这样构建cat_dictval_dict:

Note that since you probably already have a dataframe, you can build cat_dict and val_dict like this:

# map categories to y-values
cat_dict = dict(zip(pandas.unique(df['category']), range(1, len(categories)+1)))

# map y-values to categories
val_dict = dict(zip(range(1, len(categories)+1), pandas.unique(df['category'])))

这篇关于Matplotlib时间轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆