Matplotlib - 为某些数据点绘制不同的颜色 [英] Matplotlib - plot with a different color for certain data points

查看:101
本文介绍了Matplotlib - 为某些数据点绘制不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question is similar to this question. I am plotting latitude vs longitude. If the value in a variable is 0, I want that lat/long value to be marked with a different color. How do I do that?

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

This is my attempt at it so far. Here x holds the latitude and y holds longitude. timeDiff is a list holding float values and if the value is 0.0, I want that color to be different.

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

Since, matplotlib complained that it cannot use floats, I first converted the values to 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 的长度.他们都是一样的.有人可以帮我解决这个问题吗?谢谢.

So I checked the lengths of x, y and timeDiffInt. All of them are the same. Can someone please help me with this? Thanks.

推荐答案

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

You are indexing your timeDiffInt list with items from that list, if those are integers larger then the length of the list, it will show this error.

您是否希望散点图包含两种颜色?0 值的一种颜色和其他值的另一种颜色?

Do you want your scatter to contain two colors? One colors for values of 0 and another colors for other values?

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

You can use Numpy to change your list to zeros and ones:

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

Scatter 将对两个值使用不同的颜色.

Scatter will then use different colors for both values.

fig, ax = plt.subplots(figsize=(5,5))

ax.scatter(x,y,c=timeDiffInt, s=150, marker='<', edgecolor='none')

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

You can create colors for specific values by making a colormap yourself:

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)

这篇关于Matplotlib - 为某些数据点绘制不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆