Matplotlib - plot with a different color for certain data points

不想你离开。 提交于 2019-12-10 09:25:00

问题


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?

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.

Since, matplotlib complained that it cannot use floats, I first converted the values to 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. All of them are the same. Can someone please help me with this? Thanks.


回答1:


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.

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

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

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

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')

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)


来源:https://stackoverflow.com/questions/19311498/matplotlib-plot-with-a-different-color-for-certain-data-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!