在 matplotlib 中绘制二进制时间线 [英] Plot a binary timeline in matplotlib
问题描述
我正在尝试使用 matplotlib 绘制二进制时间线(不过,我可能会考虑其他库).
现在,二进制时间线"是指按时间顺序显示的事件,其中事件空间由两个相反的事件组成".此类事件空间的示例可以是 {no_one_in_the_team_is_sick, at_least_one_person_in_the_team_is_sick}
.
我想复制的表示是这样的(我使用 d3 做到了):
我曾尝试探索使用堆叠的水平条,但它显然不是适合这项工作的工具.
是否有更简单和/或更正确的方法来实现该结果?
您可以使用
将 numpy 导入为 np将熊猫导入为 pd导入 matplotlib.pyplot 作为 plt导入 matplotlib.dates#创建一个时间序列s,日期为索引,事件为0和1日期 = pd.date_range("2017-04-01","2017-06-15", freq="D")事件 = np.random.random_integers(0,1,size=len(dates))s = pd.Series(事件,索引=日期)图, ax= plt.subplots(figsize=(6,2))# 为事件==1绘制绿色s1 = s[s == 1]inxval = matplotlib.dates.date2num(s1.index.to_pydatetime())时间 = zip(inxval, np.ones(len(s1)))plt.broken_barh(times, (-1,1), color="green")# 为事件==0绘制红色s2 = s[s == 0]inxval = matplotlib.dates.date2num(s2.index.to_pydatetime())时间 = zip(inxval, np.ones(len(s2)))plt.broken_barh(times, (-1,1), color="red")#格式化轴ax.margins(0)ax.set_yticks([])ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator())ax.xaxis.set_minor_locator(matplotlib.dates.DayLocator())monthFmt = matplotlib.dates.DateFormatter("%b")ax.xaxis.set_major_formatter(monthFmt)plt.tight_layout()plt.show()
I'm trying to plot a binary timeline using matplotlib (I might be able to consider alternative libraries, though).
Now, by "binary timeline" I mean the "display of chronological events, where the event space is made of two opposite events".
An example of such an event space could be {no_one_in_the_team_is_sick, at_least_one_person_in_the_team_is_sick}
.
The representation I'd like to replicate is this (I did it using d3):
I've tried exploring the use of stacked horizontal bars, but it's clearly not the right tool for the job.
Is there an easier and/or more correct way of achieving that result?
You may use broken_barh
to plot a binary timeline.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates
#create a time series s with dates as index and 0 and 1 for events
dates = pd.date_range("2017-04-01","2017-06-15", freq="D")
events = np.random.random_integers(0,1,size=len(dates))
s = pd.Series(events, index=dates)
fig, ax= plt.subplots(figsize=(6,2))
# plot green for event==1
s1 = s[s == 1]
inxval = matplotlib.dates.date2num(s1.index.to_pydatetime())
times= zip(inxval, np.ones(len(s1)))
plt.broken_barh(times, (-1,1), color="green")
# plot red for event==0
s2 = s[s == 0]
inxval = matplotlib.dates.date2num(s2.index.to_pydatetime())
times= zip(inxval, np.ones(len(s2)))
plt.broken_barh(times, (-1,1), color="red")
#format axes
ax.margins(0)
ax.set_yticks([])
ax.xaxis.set_major_locator(matplotlib.dates.MonthLocator())
ax.xaxis.set_minor_locator(matplotlib.dates.DayLocator())
monthFmt = matplotlib.dates.DateFormatter("%b")
ax.xaxis.set_major_formatter(monthFmt)
plt.tight_layout()
plt.show()
这篇关于在 matplotlib 中绘制二进制时间线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!