0

I have some data like y = [5,3,1,9,4, 3,4,5,7,8, 8,3,2,9,5, 3,6,9,9,6] and I want to plot these values as points in a scatter plot, in the given order. Using matplotlib, the right "geometry" is given by plt.scatter(range(len(y)),y). However, the data comes in groups. The first five data points are in the first group, the second five in the second group, etc. And I have a list storing the group labels. group = [1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3, 4,4,4,4,4, 5,5,5,5,5].

What I now want to do have the same plot as plt.scatter(range(len(y)),y), but where the first group is colored blue in the plot, the second colored red, third colored green, fourth black, fifth purple. In effect this is like using coloring to represent a third axis along which the data is measured. I've seen a solution where you just call plot.scatter five times, but for a couple reasons I'd like to try to do this using the cmap parameter instead.

I've tried

import matplotlib.pyploy as plt

y = [5,3,1,9,4, 3,4,5,7,8, 8,3,2,9,5, 3,6,9,9,6]
group = [1,1,1,1,1, 2,2,2,2,2, 3,3,3,3,3, 4,4,4,4,4, 5,5,5,5,5]

plt.scatter(range(20), y, c=group, cmap=['b','r','g','black','magenta'])

but this didn't work. I've tried reading up on how to use cmap but every example I find is either a little off from how my data is structured, or wildly complicated. I could restructure my data to fit those examples, but something tells me there should be an easier way.

1 Answer 1

1

Your example is not clear - either you have four groups with five data points or five groups with four data points. Anyhow, you either use a standard colormap or you have to register your own:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

y =     [5,3,1,9, 4,3,4,5, 7,8,8,3, 2,9,5,3, 6,9,9,6]
group = [1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5]

my_cmap = ListedColormap(['b','r','g','black','magenta'])

plt.scatter(range(len(y)), y, c=group, cmap=my_cmap)
plt.show()

Sample output:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.