序列索引图python

2024-09-29 19:06:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图绘制一组按时间排序的值的序列,其中每个值用不同的颜色表示。例如,如果我的价值观是

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以一种微不足道的方式来完成这件事

^{pr2}$

这给了我一些类似的东西(这个输出可能与代码片段不完全匹配-为了更好地清晰起见,我编辑了代码) 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?


Tags: 代码元素time排序颜色时间绘制序列
1条回答
网友
1楼 · 发布于 2024-09-29 19:06:21

我假设您希望每个值都是方形框,而不考虑每个值之间的时间间隔。要有一个表示时间间隔的宽度,可以convert ^{} 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

相关问题 更多 >

    热门问题