python - Matplotlib 时间线

标签 python matplotlib pandas timeline

我正在寻找一个带有一堆时间轴的 python DataFrame,并将它们绘制在一个图中。 DataFrame 索引是时间戳,并且有一个特定的列,我们称之为“序列”,其中包含像“A”和“B”这样的字符串。所以 DataFrame 看起来像这样:

+--------------------------+---+
| 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 |
+--------------------------+---+

我正在寻找这样的情节:

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

最佳答案

我会使用字典将每个类别映射到一个 y 值。

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)))

然后我得到:

enter image description here

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

# 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'])))

关于python - Matplotlib 时间线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041905/

相关文章:

python - PyQt:以编程方式创建 QT 小部件

python - 基于多个字典转换数据

python - Matplotlib imshow - 'speed up' 某些值范围内的颜色变化

python - 是否有一种灵活的方法可以通过从形状文件读取或使用一组顶点创建的多边形来裁剪光栅?

python - 在 plt.show() 之后指定 Matplotlib 中缩放图像的高度和宽度

python - 如何在多线程任务/时间图中可视化线程?

python - 根据另一列的条件连接一列的字符串

python - Pandas 在日期列上重新采样

python - 转换数据框

python - 如何检测 sys.stdout 是否连接到终端?