matplotlib: how to change data points color based on some variable

后端 未结 2 533
北海茫月
北海茫月 2020-11-27 03:11

I have 2 variables (x,y) that change with time (t). I want to plot x vs. t and color the ticks based on the value of y. e.g. for highest values of y the tick color is dark g

相关标签:
2条回答
  • 2020-11-27 03:43

    If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

    def plot(xx, yy, good):
        """Plot data
    
        Good parts are plotted as black, bad parts as red.
    
        Parameters
        ----------
        xx, yy : 1D arrays
            Data to plot.
        good : `numpy.ndarray`, boolean
            Boolean array indicating if point is good.
        """
        import numpy as np
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots()
        from matplotlib.colors import from_levels_and_colors
        from matplotlib.collections import LineCollection
        cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
        points = np.array([xx, yy]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lines = LineCollection(segments, cmap=cmap, norm=norm)
        lines.set_array(good.astype(int))
        ax.add_collection(lines)
        plt.show()
    
    0 讨论(0)
  • 2020-11-27 03:49

    This is what matplotlib.pyplot.scatter is for.

    As a quick example:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate data...
    t = np.linspace(0, 2 * np.pi, 20)
    x = np.sin(t)
    y = np.cos(t)
    
    plt.scatter(t,x,c=y)
    plt.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题