How to draw a bar timeline with matplotlib?

淺唱寂寞╮ 提交于 2019-12-04 10:16:46

I don't think there is the need to for a special function here. Using plt.barh is directly giving you the desired plot.

import matplotlib.pyplot as plt
import numpy as np

begin = np.array([2003,1991,2008,1986,2013,1994,2002])
end =   np.array([2007,2016,2016,2015,2013,1999,2002])
event = ["Event {}".format(i) for i in range(len(begin))]

plt.barh(range(len(begin)),  end-begin, left=begin)

plt.yticks(range(len(begin)), event)
plt.show()

Note that Event 4 and 6 seem missing, because start and end are identical. If you want to interprete end as being the end of the year, you may add 1 to it,

plt.barh(range(len(begin)),  end-begin+1, left=begin)

Made a different serialsation of input data as below, a bit more natural for the incoming data:

events = [('Event 0', 2003, 2007),
     ('Event 1', 1991, 2016),
     ('Event 2', 2008, 2016)
     #...
     ]

Also wrapped in a function, as question author may have wanted.

See at https://github.com/epogrebnyak/hrange/blob/master/hrange.py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!