0

In order to display a very simple timeline of Ancient History (inspired by Wolfram Alpha timelines), I have slightly modified a small python program found on S.O. (How to draw a bar timeline with matplotlib?) :

import matplotlib.pyplot as plt
import numpy as np

event = np.array(['Antiquity','Egypt','W.R.Empire','E.R.Empire','Writing','C.Colomb','Middle Ages'])
begin = np.array([-3400,-3150,285,330,-3400,1492,476])
end = np.array([476,30,476,1453,-3300,1493,1492])

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

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

plt.show()

How can I sort (ascending) the timeline by the beginning date ? The reason is that I wish to enter the data as they come (Minoans, Elam, etc...) without having to rearrange the arrays each time, which would be tedious.

This is not homework. I am simply a Python newbie, and I can't figure how to answer my own question…

ThG
  • 2,361
  • 4
  • 22
  • 33
  • You probably misunderstood the concept of a Q&A. You ask one specific question and get one or more answers to that question. Now it seems each of those question have already been asked before. If not, then each question to which there is no answer here on SO deserves its own question and answer. – ImportanceOfBeingErnest Feb 22 '18 at 21:36
  • @ImportanceOfBeingErnest : I edited the question… – ThG Feb 23 '18 at 08:14

1 Answers1

1

You may want to sort your values.

import matplotlib.pyplot as plt
import numpy as np

event = np.array(['Antiquity','Egypt','W.R.Empire','E.R.Empire','Writing','Middle Ages'])
begin = np.array([-3400,-3150,285,330,-3400,476])
end = np.array([476,30,476,1453,-3300,1493])

beg_sort = np.sort(begin)
end_sort = end[np.argsort(begin)]
evt_sort = event[np.argsort(begin)]

plt.barh(range(len(beg_sort)), end_sort-beg_sort, left=beg_sort, align='center')

plt.yticks(range(len(beg_sort)), evt_sort)

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • (nice name, by the way : you are not Lady Bracknell, after all…) : it works. Thank you very much ! May I ask a side question : is it possible to have it the Gantt way (from tpo left to bottom right) ? This is only a side question : dismiss it if you wish. Thanks again. – ThG Feb 23 '18 at 11:24
  • Do you want to [reverse the axis direction](https://stackoverflow.com/questions/2051744/reverse-y-axis-in-pyplot)? – ImportanceOfBeingErnest Feb 23 '18 at 11:25
  • Yes : Antiquity at the top, Middle Ages at the bottom. Sorry for being a nuisance… – ThG Feb 23 '18 at 11:28
  • Done. Thanks to you. – ThG Feb 23 '18 at 11:35
  • @ThG +1 if you share how you did it – abu Nov 16 '22 at 20:38