如何在实体重复时绘制断裂条形图(乐队成员任职场景)
解决乐队成员多次加入的断裂条形图绘制问题
要实现每个成员在y轴仅显示一次、对应多段断裂条形的需求,核心是给每个成员绑定固定的y轴位置,然后按成员分组遍历所有时间段,逐个绘制水平条形。以下是修改后的完整代码:
import matplotlib.pyplot as plt import pandas as pd 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']) print(result) fig, ax = plt.subplots() persons = result.Person.unique() person_count = len(persons) ybound = len(persons)*10 ystep = int(ybound/person_count) numbers = range(5, ybound, ystep) # 建立成员与y轴位置的映射字典 person_y_pos = dict(zip(persons, numbers)) ax.set_ylim(0, ybound) ax.set_xlim(min(result.Year_start)-1, max(result.Year_left)+1) ax.set_xlabel('Years') ax.set_yticks(numbers, labels=persons) # 按成员分组遍历,绘制每个成员的所有时间段条形 for person, group in result.groupby('Person'): y_pos = person_y_pos[person] # 遍历该成员的每一段任职时间 for _, row in group.iterrows(): start_year = row['Year_start'] duration = row['Year_left'] - start_year # 绘制水平条形,设置高度为ystep的0.8倍,避免重叠 ax.barh(y_pos, duration, left=start_year, height=ystep*0.8, align='center') ax.grid(True) plt.show()
关键步骤说明:
- 成员与y轴位置绑定:用
zip将唯一成员列表和对应的y轴刻度位置打包成字典,确保每个成员始终对应同一个y坐标。 - 分组遍历数据:通过
groupby('Person')按成员分组,一次性处理某一成员的所有任职时间段。 - 绘制多段条形:对每个成员的每一段任职记录,计算时长(结束年份-开始年份),用
barh绘制水平条形,通过left参数设置条形的起始年份,height参数控制条形高度,避免和其他成员的条形重叠。
内容的提问来源于stack exchange,提问作者muted_buddy
相关产品推荐
相关产品推荐

