【问题标题】:How to change data points color based on some variable如何根据某些变量更改数据点颜色
【发布时间】:2011-12-14 11:36:17
【问题描述】:

我有 2 个随时间 (t) 变化的变量 (x,y)。我想绘制 x 与 t 并根据 y 的值对刻度进行着色。例如对于 y 的最高值,刻度颜色为深绿色,最低值为深红色,对于中间值,颜色将在绿色和红色之间缩放。

这可以用 python 中的 matplotlib 完成吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    这就是matplotlib.pyplot.scatter 的用途。

    如果未指定颜色图,scatter 将使用默认颜色图设置的任何值。要指定应该使用哪个颜色图散点图,请使用 cmap kwarg(例如 cmap="jet")。

    举个简单的例子:

    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    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, ec='k')
    plt.show()
    

    可以指定自定义颜色图和规范

    cmap, norm = mcolors.from_levels_and_colors([0, 2, 5, 6], ['red', 'green', 'blue'])
    plt.scatter(x, y, c=t, cmap=cmap, norm=norm)
    

    【讨论】:

    • 非常感谢。感谢您的快速响应。
    【解决方案2】:

    如果您想绘制线而不是点,请参阅this example,在此处修改以绘制将函数表示为适当的黑色/红色的好/坏点:

    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()
    

    【讨论】:

      猜你喜欢
      • 2013-11-30
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多