下面的代码示例绘制了一个虚线Barh图,其中包含在一段时间内加入和离开音乐乐队的人员列表:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
result = pd.DataFrame([['Bill', 1972, 1974],
['Bill', 1976, 1978],
['Bill', 1967, 1971],
['Danny', 1969, 1975],
['Danny', 1976, 1977],
['James', 1971, 1972],
['Marshall', 1967, 1975]],
columns=['Person', 'Year_start', 'Year_left'])
fig, ax = plt.subplots()
names = sorted(result['Person'].unique())
colormap = plt.get_cmap('plasma')
slicedColorMap = colormap(np.linspace(0, 1, len(names)))
height = 0.5
for y, (name, g) in enumerate(result.groupby('Person')):
ax.broken_barh(list(zip(g['Year_start'],
g['Year_left']-g['Year_start'])),
(y-height/2, height),
facecolors=slicedColorMap[y]
)
ax.set_ylim(0-height, len(names)-1+height)
ax.set_xlim(result['Year_start'].min()-1, result['Year_left'].max()+1)
ax.set_yticks(range(len(names)), names)
ax.grid(True)
plt.show()
The output result is this diagram:
我需要按‘Year_Start’和‘Year_Left’对条形图(以及y轴上的人员)进行排序,两者都是按升序排列的.
我知道如何在数据分组后对DataFrame中的值进行聚合和排序,并且应该在之后重置索引:
sorted_result = result.groupby('Person').agg({'Year_start': min, 'Year_left': max})
sorted_result = sorted_result.sort_values(['Year_start', 'Year_left'], ascending=[True, True]).reset_index()
print(sorted_result)
但是,在绘制ax.rupt_barh时,我很难将这种排序嵌入到现有的"for in"循环中(正如我所理解的,这也是因为不可能在单个迭代中使用"agg"使用"groupby"来执行"sortValues"). 在这个脚本中是否可以进行这种排序,或者我应该完全重新考虑脚本 struct ? 非常感谢!