【问题标题】:Plot a binary timeline in matplotlib在 matplotlib 中绘制二进制时间线
【发布时间】:2017-07-06 14:33:42
【问题描述】:

我正在尝试使用 matplotlib 绘制二进制时间线(不过,我也许可以考虑使用其他库)。

现在,“二进制时间线”是指“按时间顺序显示的事件,其中事件空间由两个相反的事件组成”。 {no_one_in_the_team_is_sick, at_least_one_person_in_the_team_is_sick} 是此类事件空间的一个示例。

我想复制的表示是这样的(我使用 d3 完成了):

我尝试过使用堆叠的水平条,但它显然不是适合这项工作的工具。

是否有更简单和/或更正确的方法来实现该结果?

【问题讨论】:

  • 能否提供少量样本数据?
  • 您也可以查看this question,它提供了一些可能但不是完美的解决方案。
  • @jadsq 一个最小的例子可能是[(391030.0, True), (63202.0, False), (150568.0, True)],其中每个元组中的数字是框的宽度,第二个是二进制事件。 @ImportanceOfBeingErnest 使用scatter 的解决方案很简洁,但主要缺点是它显示点,所以会有空白(除非我将所有数据标准化为所有宽度的gcd,我想避免这种情况);使用 PIL 的解决方案也不错,但目前似乎有点过头了。

标签: python matplotlib plot timeline


【解决方案1】:

您可以使用broken_barh来绘制二进制时间线。

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 的示例,但我没有发现 broken_barh。感谢您指出 - 我相信我可以根据自己的需要调整它!
  • 如果有人必须将timedelta64 转换为浮点数以便绘制具有给定宽度的框(而不是像上面的示例中那样使用np.ones),我已经采取了 -假设您有一个带有“持续时间”列的 DataFrame - 是df.duration.map(pd.Timedelta.to_pytimedelta) / np.timedelta64(1, 'D')。这基本上以天为单位返回持续时间,类似于 date2num 对日期所做的操作。
【解决方案2】:

这可能对你有用:

Rich Matplotlib timeline visualization

它确实显示了比您可能需要的更丰富的信息。

【讨论】:

  • 相当整洁!感谢您的链接。
猜你喜欢
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2010-12-07
  • 2019-08-14
  • 2016-04-18
相关资源
最近更新 更多