Matplotlib plot with variable line width

前端 未结 4 1158
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 14:00

Is it possible to plot a line with variable line width in matplotlib? For example:

from pylab import *
x = [1, 2, 3, 4, 5]
y = [1, 2, 2, 0, 0]
width = [.5,          


        
4条回答
  •  [愿得一人]
    2020-11-27 14:18

    gg349's answer works nicely but cuts the line into many pieces, which can often creates bad rendering.

    Here is an alternative example that generates continuous lines when the width is homogeneous:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots(1)
    xs = np.cos(np.linspace(0, 8 * np.pi, 200)) * np.linspace(0, 1, 200)
    ys = np.sin(np.linspace(0, 8 * np.pi, 200)) * np.linspace(0, 1, 200)
    widths = np.round(np.linspace(1, 5, len(xs)))
    
    def plot_widths(xs, ys, widths, ax=None, color='b', xlim=None, ylim=None,
                    **kwargs):
        if not (len(xs) == len(ys) == len(widths)):
            raise ValueError('xs, ys, and widths must have identical lengths')
        fig = None
        if ax is None:
            fig, ax = plt.subplots(1)
    
        segmentx, segmenty = [xs[0]], [ys[0]]
        current_width = widths[0]
        for ii, (x, y, width) in enumerate(zip(xs, ys, widths)):
            segmentx.append(x)
            segmenty.append(y)
            if (width != current_width) or (ii == (len(xs) - 1)):
                ax.plot(segmentx, segmenty, linewidth=current_width, color=color,
                        **kwargs)
                segmentx, segmenty = [x], [y]
                current_width = width
        if xlim is None:
            xlim = [min(xs), max(xs)]
        if ylim is None:
            ylim = [min(ys), max(ys)]
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
    
        return ax if fig is None else fig
    
    plot_widths(xs, ys, widths)
    plt.show()
    

提交回复
热议问题