Changing the linewidth and the color simultaneously in matplotlib

前端 未结 2 574
青春惊慌失措
青春惊慌失措 2020-12-31 20:23

The figure above is a great artwork showing the wind speed, wind direction and temperature simultaneously. detailedly:

  • The X axes represent the date
2条回答
  •  自闭症患者
    2020-12-31 21:07

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    x = np.linspace(0,4*np.pi,10000) # x data
    y = np.cos(x) # y data
    r = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [lambda x: 1-x/(2*np.pi), 0]) # red
    g = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [lambda x: x/(2*np.pi), lambda x: -x/(2*np.pi)+2]) # green
    b = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [0, lambda x: x/(2*np.pi)-1]) # blue
    
    a = np.ones(10000) # alpha
    w = x # width
    
    fig, ax = plt.subplots(2)
    
    ax[0].plot(x, r, color='r')
    ax[0].plot(x, g, color='g')
    ax[0].plot(x, b, color='b')
    
    # mysterious parts
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    # mysterious parts
    
    rgba = list(zip(r,g,b,a))
    
    lc = LineCollection(segments, linewidths=w, colors=rgba)
    
    ax[1].add_collection(lc)
    ax[1].set_xlim(0,4*np.pi)
    ax[1].set_ylim(-1.1,1.1)
    fig.show()
    

    I notice this is what I suffered.

提交回复
热议问题