How to sort a historical timeline written with Pyt

2019-08-25 02:48发布

问题:

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…

回答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()