python - Matplotlib - 为某些数据点绘制不同的颜色

标签 python matplotlib scatter

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

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

因为 matplotlib 提示它不能使用 float ,所以我首先将值转换为 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 的长度。他们都是一样的。有人可以帮我吗?谢谢。

最佳答案

您正在使用该列表中的项目索引您的 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')

enter image description here

编辑:

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

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)

关于python - Matplotlib - 为某些数据点绘制不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19311498/

相关文章:

python - Django 没有使用 manage.py 测试运行测试

python - 我的 CNN 总是得出 0 或 1,而不是百分比。为什么?

python - 如何在 Matplotlib 中绘制不同颜色的图

python - 在 Abaqus 6.12 中使用 matplotlib(适用于 python 2.6)

python - matplotlib 散点图颜色作为第三个变量的函数

javascript - 分散的无序列表

python - 在 python 中保存元组的最佳方法是什么

python - 对曲线上定期采样的 2D 点列表进行排序

python - Matplotlib:如何使两个直方图具有相同的 bin 宽度?

python - 散点图上的颜色 Python Matplotlib