【问题标题】:Matplotlib - plot with a different color for certain data pointsMatplotlib - 为某些数据点绘制不同颜色的图
【发布时间】:2013-10-11 06:19:28
【问题描述】:

我的问题类似于this question。我正在绘制纬度与经度。如果变量中的值为 0,我希望用不同的颜色标记该纬度/经度值。我该怎么做?

这是我迄今为止的尝试。这里 x 保存纬度,y 保存经度。 timeDiff 是一个包含浮点值的列表,如果值为 0.0,我希望该颜色不同。

由于 matplotlib 抱怨它不能使用浮点数,我首先将值转换为 int。

timeDiffInt=[int(i) for i in timeDiff]

然后我使用列表推导:

plt.scatter(x,y,c=[timeDiffInt[a] for a in timeDiffInt],marker='<')

但我收到此错误:

IndexError: list index out of range

所以我检查了 x、y 和 timeDiffInt 的长度。他们都是一样的。有人可以帮我吗?谢谢。

【问题讨论】:

    标签: python matplotlib scatter


    【解决方案1】:

    您正在使用该列表中的项目索引您的 timeDiffInt 列表,如果这些整数大于列表的长度,则会显示此错误。

    您希望散布包含两种颜色吗?一种颜色代表 0 值,另一种颜色代表其他值?

    您可以使用 Numpy 将列表更改为零和一:

    timeDiffInt = np.where(np.array(timeDiffInt) == 0, 0, 1)
    

    Scatter 将为这两个值使用不同的颜色。

    fig, ax = plt.subplots(figsize=(5,5))
    
    ax.scatter(x,y,c=timeDiffInt, s=150, marker='<', edgecolor='none')
    

    编辑:

    您可以通过自己制作颜色图来为特定值创建颜色:

    fig, ax = plt.subplots(figsize=(5,5))
    
    colors = ['red', 'blue']
    levels = [0, 1]
    
    cmap, norm = mpl.colors.from_levels_and_colors(levels=levels, colors=colors, extend='max')
    
    ax.scatter(x,y,c=timeDiffInt, s=150, marker='<', edgecolor='none', cmap=cmap, norm=norm)
    

    【讨论】:

    • 太棒了。非常感谢你。这一行中的“无花果”是做什么的?无花果,斧头 = plt.subplots(figsize=(5,5))
    • 另外,如何更改颜色?红色表示零值。
    • 查看编辑。 fig 是图形对象,它包含轴和绘制的所有内容。如果您使用plt.scatter(),它会在后台创建。
    • 也许我遗漏了一些东西,但你真的是指timeDiffInt 而不是z?如果不是,z 是什么?
    猜你喜欢
    • 2013-02-26
    • 2018-04-08
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    • 2018-11-28
    • 2021-01-08
    相关资源
    最近更新 更多