序列索引图python

时间:2016-08-05 10:24:55

标签: python matplotlib seaborn

我试图绘制一组时间排序值的序列,其中每个值由不同的颜色表示。例如,如果我的值类似于

state_seq = [2, 2, 2, 2, 0, 0, 0, 1, 3, 6, 3, 3, 3, 0, 0]
time_seq = ['2013-05-29 09:31:00', '2013-05-29 09:46:00', '2013-07-23 12:28:00', '2013-07-23 01:53:00', '2013-08-05 02:02:00', '2013-08-05 02:08:00', '2013-08-05 04:28:00', '2013-08-06 10:20:00', '2013-08-06 03:03:00', '2013-08-06 04:13:00', '2013-08-06 04:17:00', '2013-08-06 04:36:00', '2013-08-07 11:07:00', '2013-08-07 12:28:00', '2013-08-07 12:31:00']

我希望state_seq的每个唯一元素用颜色表示并绘制序列。截至目前,我正在使用seaborn palplot以一种微不足道的方式完成这项工作,

color_set = ["#95a5a6", "#34495e","#9b59b6", "#3498db", "#800000", "#2ecc71", 'y', '#FF4500']
palette = list()
for s in state_seq:
  palette.append(color_set[s])    

sns.palplot(palette)

这给了我这样的东西(这个输出可能与代码片段完全不匹配 - 为了更清晰,我编辑了代码) Sequence from seaborn pal plot

这种方法有一个挫折,我无法在x轴上表示我的时间标签。有没有更好的python替代方案,可能类似于此处解释的R-package TraMineR Is it possible to make a graph with pattern fills using TraMineR and R base graphs?

1 个答案:

答案 0 :(得分:2)

我假设你想要每个值的方框,而不管每个值之间的时间间隔。要有一个指示时间间隔的宽度convert time_seq to datetime objects,然后直接用matplotlib绘制日期。

import matplotlib.pyplot as plt
import numpy as np

state_seq = [2, 2, 2, 2, 0, 0, 0, 1, 3, 6, 3, 3, 3, 0, 0]
time_seq = ['2013-05-29 09:31:00', '2013-05-29 09:46:00', '2013-07-23 12:28:00', '2013-07-23 01:53:00', '2013-08-05 02:02:00', '2013-08-05 02:08:00', '2013-08-05 04:28:00', '2013-08-06 10:20:00', '2013-08-06 03:03:00', '2013-08-06 04:13:00', '2013-08-06 04:17:00', '2013-08-06 04:36:00', '2013-08-07 11:07:00', '2013-08-07 12:28:00', '2013-08-07 12:31:00']
color_set = ["#95a5a6", "#34495e","#9b59b6", "#3498db", "#800000", "#2ecc71", 'y', '#FF4500']

for i in range(len(time_seq)):
    # fill the yaxis with our colour for each time_seq entry for width 1
    plt.fill_between((i,i+1), 1, color=color_set[state_seq[i]])

# keep the coloured boxes square
plt.axis("scaled")

plt.xlim(0, len(time_seq))
plt.axes().get_yaxis().set_visible(False)

# add custom tick labels based on time_seq and set to middle of boxes
plt.xticks(np.arange(0.5,len(time_seq)+0.5, 1),  time_seq, rotation='vertical')
# remove xaxis ticks
plt.axes().get_xaxis().set_ticks_position("none")

plt.savefig("boxes.png", bbox_inches="tight")

产地: enter image description here