Matplotlib - plot with a different color for certain data points

Sarvavyapi picture Sarvavyapi · Oct 11, 2013 · Viewed 20.5k times · Source

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.

Answer

Rutger Kassies picture Rutger Kassies · Oct 11, 2013

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

enter image description here

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)