How to draw vertical lines on a given plot in matplotlib

后端 未结 6 653
我寻月下人不归
我寻月下人不归 2020-11-28 18:27

Given a plot of signal in time representation, how to draw lines marking corresponding time index?

Specifically, given a signal plot with time index ranging from 0 t

6条回答
  •  遥遥无期
    2020-11-28 19:27

    Calling axvline in a loop, as others have suggested, works, but can be inconvenient because

    1. Each line is a separate plot object, which causes things to be very slow when you have many lines.
    2. When you create the legend each line has a new entry, which may not be what you want.

    Instead you can use the following convenience functions which create all the lines as a single plot object:

    import matplotlib.pyplot as plt
    import numpy as np
    
    
    def axhlines(ys, ax=None, lims=None, **plot_kwargs):
        """
        Draw horizontal lines across plot
        :param ys: A scalar, list, or 1D array of vertical offsets
        :param ax: The axis (or none to use gca)
        :param lims: Optionally the (xmin, xmax) of the lines
        :param plot_kwargs: Keyword arguments to be passed to plot
        :return: The plot object corresponding to the lines.
        """
        if ax is None:
            ax = plt.gca()
        ys = np.array((ys, ) if np.isscalar(ys) else ys, copy=False)
        if lims is None:
            lims = ax.get_xlim()
        y_points = np.repeat(ys[:, None], repeats=3, axis=1).flatten()
        x_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(ys), axis=0).flatten()
        plot = ax.plot(x_points, y_points, scalex = False, **plot_kwargs)
        return plot
    
    
    def axvlines(xs, ax=None, lims=None, **plot_kwargs):
        """
        Draw vertical lines on plot
        :param xs: A scalar, list, or 1D array of horizontal offsets
        :param ax: The axis (or none to use gca)
        :param lims: Optionally the (ymin, ymax) of the lines
        :param plot_kwargs: Keyword arguments to be passed to plot
        :return: The plot object corresponding to the lines.
        """
        if ax is None:
            ax = plt.gca()
        xs = np.array((xs, ) if np.isscalar(xs) else xs, copy=False)
        if lims is None:
            lims = ax.get_ylim()
        x_points = np.repeat(xs[:, None], repeats=3, axis=1).flatten()
        y_points = np.repeat(np.array(lims + (np.nan, ))[None, :], repeats=len(xs), axis=0).flatten()
        plot = ax.plot(x_points, y_points, scaley = False, **plot_kwargs)
        return plot
    

提交回复
热议问题