简体   繁体   English

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

[英]Matplotlib - plot with a different color for certain data points

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. 如果变量中的值为0,我希望使用不同的颜色标记lat / long值。 How do I do that? 我怎么做?

This is my attempt at it so far. 到目前为止,这是我的尝试。 Here x holds the latitude and y holds longitude. 这里x保持纬度,y保持经度。 timeDiff is a list holding float values and if the value is 0.0, I want that color to be different. timeDiff是一个包含浮点值的列表,如果值为0.0,我希望该颜色不同。

Since, matplotlib complained that it cannot use floats, I first converted the values to int. 因为,matplotlib抱怨它不能使用浮点数,我首先将值转换为int。

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

Then I used list comprehension: 然后我使用了列表理解:

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

But I get this error: 但我得到这个错误:

IndexError: list index out of range

So I checked the lengths of x, y and timeDiffInt. 所以我检查了x,y和timeDiffInt的长度。 All of them are the same. 所有这些都是一样的。 Can someone please help me with this? 有人可以帮我这个吗? Thanks. 谢谢。

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. 您正在使用该列表中的项目索引timeDiffInt列表,如果这些是大于列表长度的整数,则会显示此错误。

Do you want your scatter to contain two colors? 你想要你的散射包含两种颜色吗? One colors for values of 0 and another colors for other values? 值为0的一种颜色和其他值的另一种颜色?

You can use Numpy to change your list to zeros and ones: 您可以使用Numpy将列表更改为0和1:

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

Scatter will then use different colors for both values. 然后,Scatter将为这两个值使用不同的颜色。

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

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

在此输入图像描述

edit: 编辑:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM