我想画一张条形图,上面列出了加入和离开一支音乐乐队的乐队成员. 我设法画了一个我想要的网格,但我坚持为乐队成员画线条,因为他们在重复. 当乐队成员是唯一的,但日期列重复时,我知道如何创建,F.E.:Year_Start1、Year_End1、Year_START2、Year_End2等. 但当乐队成员在复制时,他们就会被困住. 因此,每个人应该在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)

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)


ax.grid(True)
plt.show()

我想我应该使用"for"循环并将数据帧放入"Zip"中,但不确定具体如何操作.

推荐答案

不确定您到底想要什么,但您可以手动绘制条形图:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

ys = {k: i for i, k in enumerate(result['Person'].unique())}

ax = plt.subplot()

height = 0.5

for row in result.itertuples():
    y = ys[row.Person]
    x0 = row.Year_start
    x1 = row.Year_left
    #                         bottom left corner  width    height
    rect = mpatches.Rectangle((x0, y - height/2), x1 - x0, height,
                              facecolor='grey')
    ax.add_patch(rect)

ax.set_ylim(0-height, len(ys)-1+height)
ax.set_xlim(result['Year_start'].min()-1, result['Year_left'].max()+1)
ax.set_yticks(range(len(ys)), list(ys))

NB. Danny has overlapping dates, which are thus overlapping. If this is not expected, please clarify.

输出:

enter image description here

using broken_barh:

ax = plt.subplot()

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)
                   )
names = sorted(result['Person'].unique())
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)

Python相关问答推荐

如何使用entry.bind(FocusIn,self.Method_calling)用于使用网格/列表创建的收件箱

如何将ctyles.POINTER(ctyles.c_float)转换为int?

点到面的Y距离

Pytest两个具有无限循环和await命令的Deliverc函数

Gekko:Spring-Mass系统的参数识别

抓取rotowire MLB球员新闻并使用Python形成表格

当我try 在django中更新模型时,模型表单数据不可见

joblib:无法从父目录的另一个子文件夹加载转储模型

如何合并两个列表,并获得每个索引值最高的列表名称?

未调用自定义JSON编码器

matplotlib图中的复杂箭头形状

如何创建引用列表并分配值的Systemrame列

找到相对于列表索引的当前最大值列表""

在二维NumPy数组中,如何 Select 内部数组的第一个和第二个元素?这可以通过索引来实现吗?

用两个字符串构建回文

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

mdates定位器在图表中显示不存在的时间间隔

如何强制向量中的特定元素在Gekko中处于优化解决方案中

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

随机森林n_估计器的计算