使用matplotlib绘制细分线

时间:2016-01-28 16:11:27

标签: python matplotlib

我想绘制日期数据为x轴的线段,段线不应相互重叠。但是,结果图中有一些重叠。

这是名为 data.csv

的数据文件
event_start,event_end,event_summary,posture
07:30,07:35,setting up desk,2
07:35,07:47,"fill water bottle, wash mug -> toilet",3
07:47,10:20,work( computer work + work discussion with office mate at desk),2
10:20,10:25,toilet,3
10:25,10:42,work,2
11:42,11:44,go find supervisor ,3
11:44,13:00,work (work discussion with supervisor at desk + computer work),2
13:00,13:30,toilet --> get lunch,2
13:30,14:00,Eat lunch,2
14:00,14:05,clean up,3
14:06,14:51,work (computer work + skype),2
14:51,14:59,toilet -> kitchen to fill ater bottle -> printing,3
14:59,16:31,work,2
16:31,16:42,toilet,3
16:42,17:15,work,2

以下是绘图的代码

import pandas as pd
import matplotlib.pyplot as plt
# plt.style.use('ggplot')

def plot_event(file_name, y_min=0, y_max=5):
    df = pd.read_csv(file_name)
    df['event_start'] = pd.to_datetime(df['event_start'])
    df['event_end'] = pd.to_datetime(df['event_end'])

    xs = zip(df['event_start'], df['event_end'])
    ys = zip(df['posture'], df['posture'])
    plt.ylim(y_min, y_max)
    for x, y in zip(xs, ys):
        plt.plot(x, y, linewidth=linewidth)
    plt.show()


if __name__ == '__main__':
    file_name = 'data.csv'
    y_min = 1
    y_max = 5
    linewidth = 8
    plot_event(file_name, y_min, y_max)

这是图,不同段之间有重叠。它是有线的,因为日期不重叠。 enter image description here

1 个答案:

答案 0 :(得分:2)

这可能是由线条默认绘图样式引起的。

您可能希望将solid_capstylesolid_joinstyle参数用于plt.plot()。例如:

plt.plot(x, y, linewidth=linewidth, solid_capstyle='butt')

会不会:

enter image description here

您还可以考虑使用线宽添加重叠,以及其他线格式设置,您可以在docs

中看到