4

I have the type of following data:

Begin   End                        Event
 2003  2007                      Event 1
 1991  2016                      Event 2
 2008  2016                      Event 3
 1986  2015                      Event 4
 2013  2013                      Event 5
 1994  1999                      Event 6
 2002  2002                      Event 7

My goal is to make a timeline of these events, i.e. to draw a series of distinct straight and horizontal bars from date 1 to date 2 with the names of the events on them.

I am currently trying my luck with the barh function from matplotlib.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
baloo
  • 517
  • 1
  • 5
  • 13
  • See [How to plot a Gantt chart from multiple dataframe columns](https://stackoverflow.com/a/76426207/7758804), which uses this [accepted answer](https://stackoverflow.com/a/44519386/7758804) to create a Gantt chart with datetime axis values. – Trenton McKinney Jun 09 '23 at 00:28

2 Answers2

14

I don't think there's a need 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()

enter image description here

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)

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
0

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

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Evgeny
  • 4,173
  • 2
  • 19
  • 39