is it possible to plot timelines with matplotlib?

后端 未结 4 1910
孤街浪徒
孤街浪徒 2020-12-25 09:17

Im trying to plot dates with values like this csv.

Tue  2 Jun 16:55:51 CEST 2015,3
Wed  3 Jun 14:51:49 CEST 2015,3
Fri  5 Jun 10:31:59 CEST 2015,3
Sat  6 Jun         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-25 09:31

    I wasn't able to find the answer i was looking for so here is my take on it. This function will take in a time series, then plot a random positive and negative point within the range. By giving it a series you will allow for a label on the graph, and a second series will allow you to click on it for more data.

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import matplotlib.pyplot as plt
    import mplcursors
    import numpy as np
    
    
        # expects series, annotation, and the annotation data to be shown on click
    
    def stimeline(timeseries, annotation, onclick):
    
        neg = np.random.randint(low=-500, high=0, size=len(timeseries))
        pos = np.random.randint(low=0, high=500, size=len(timeseries))
        i = 0
        d = []
        while i < len(timeseries):
            if i < len(timeseries):
                d.append(pos[i])
                i += 1
            if i < len(timeseries):
                d.append(neg[i])
                i += 1
        (fig, ax) = plt.subplots(figsize=(8.8, 4), constrained_layout=True)
        ax.stem(timeseries, d, basefmt=' ')
        ax.set(title='Timeline')
        ax.set_ylim(-545, 545)
    
        levels = np.tile(d, int(np.ceil(len(timeseries)
                         / 6)))[:len(timeseries)]
        (markerline, stemline, baseline) = ax.stem(timeseries, levels,
                linefmt='C3-', basefmt='k-')
        plt.setp(markerline, mec='k', mfc='w', zorder=3)
        vert = np.array(['top', 'bottom'])[(levels > 0).astype(int)]
        for (d, l, r, va) in zip(timeseries, levels, annotation, vert):
            ax.annotate(
                r,
                xy=(d, l),
                xytext=(-3, np.sign(l) * 3),
                textcoords='offset points',
                va=va,
                ha='right',
                )
    
        ax.get_yaxis().set_visible(False)
        for spine in ['left', 'top', 'right']:
            ax.spines[spine].set_visible(False)
    
        mplcursors.cursor(ax).connect('add', lambda sel: \
                                      sel.annotation.set_text(onclick[sel.target.index]))
    
        ax.margins(y=0.1)
        plt.show()
    
    

提交回复
热议问题