【问题标题】:Dynamic marker colour in matplotlibmatplotlib 中的动态标记颜色
【发布时间】:2016-08-17 00:08:57
【问题描述】:

我有两个列表,其中包含一些点的 x 和 y 坐标。还有一个列表,其中为每个点分配了一些值。现在我的问题是,我总是可以使用 python 中的标记绘制点 (x,y)。我也可以手动选择标记的颜色(如本代码所示)。

import matplotlib.pyplot as plt

x=[0,0,1,1,2,2,3,3]
y=[-1,3,2,-2,0,2,3,1]
colour=['blue','green','red','orange','cyan','black','pink','magenta']
values=[2,6,10,8,0,9,3,6]

for i in range(len(x)):
    plt.plot(x[i], y[i], linestyle='none', color=colour[i], marker='o')

plt.axis([-1,4,-3,4])
plt.show()

但是是否可以根据分配给该点的值(使用 cm.jet、cm.gray 或类似的其他配色方案)为标记特定点的标记选择一种颜色,并为绘图提供一个颜色条?

例如,这就是我正在寻找的那种情节

其中红点表示高温点,蓝点表示低温点,其他点表示介于两者之间的温度。

【问题讨论】:

    标签: python matplotlib markers


    【解决方案1】:

    您最有可能在寻找matplotlib.pyplot.scatter。示例:

    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate data:
    N = 10
    x = np.linspace(0, 1, N)
    y = np.linspace(0, 1, N)
    x, y = np.meshgrid(x, y)
    colors = np.random.rand(N, N) # colors for each x,y
    
    # Plot
    circle_size = 200
    cmap = matplotlib.cm.viridis # replace with your favourite colormap 
    fig, ax = plt.subplots(figsize=(4, 4))
    s = ax.scatter(x, y, s=circle_size, c=colors, cmap=cmap)
    
    # Prettify
    ax.axis("tight")
    fig.colorbar(s)
    
    plt.show()
    

    注意:viridis 在旧版本的 matplotlib 上可能会失败。 结果图像:

    编辑

    scatter 不需要您的输入数据是二维的,这里有 4 种生成相同图像的替代方法:

    import matplotlib
    import matplotlib.pyplot as plt
    
    x = [0,0,1,1,2,2,3,3]
    y = [-1,3,2,-2,0,2,3,1]
    values = [2,6,10,8,0,9,3,6]
    # Let the colormap extend between:
    vmin = min(values)
    vmax = max(values)
    
    cmap = matplotlib.cm.viridis
    norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)
    
    fig, ax = plt.subplots(4, sharex=True, sharey=True)
    # Alternative 1: using plot:
    for i in range(len(x)):
        color = cmap(norm(values[i]))
        ax[0].plot(x[i], y[i], linestyle='none', color=color, marker='o')
    
    # Alternative 2: using scatter without specifying norm
    ax[1].scatter(x, y, c=values, cmap=cmap)
    
    # Alternative 3: using scatter with normalized values:
    ax[2].scatter(x, y, c=cmap(norm(values)))
    
    # Alternative 4: using scatter with vmin, vmax and cmap keyword-arguments
    ax[3].scatter(x, y, c=values, vmin=vmin, vmax=vmax, cmap=cmap)
    
    plt.show()
    

    【讨论】:

    • 但它给了AttributeError: 'module' object has no attribute 'viridis'
    • 'viridis' 是新的 matplotlib 颜色图之一;您需要下载一个额外的模块才能使用它。你可以用'jet'替换,这是(丑陋的)matplotlib 默认
    • 好的。还有一件事,我不想做一个网格网格,我有离散点和列表 x 和 y 中给出的随机坐标。我如何用这个方案绘制它们?
    • 省略meshgrid就好了,scatter应该能搞定的:)
    • 连同colors = np.random.rand(N) 代替colors = np.random.rand(N, N)
    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 2014-08-06
    • 2015-02-05
    • 2021-12-30
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多