0

Dear experienced friends, I am curious about how to draw a scatter plot where the points with the same X-values have the same color? Suppose we have a dataset like the following:

import matplotlib.pyplot as plt

list1 = [1,1,1,1,2,2,2,2,3,3,3,3]
list2 = [9,8,10,11,1,2,1,2,4,5,6,7]

plt.scatter(list1, list2)
plt.show()

The picture looks like this: enter image description here

However, I want to draw a picture like the following one. As you can see, the points with the same x-axis value have the same color. How can I achieve this? Thank you so much in advance!

enter image description here

Nick Nick Nick
  • 159
  • 3
  • 13
  • 2
    May I interest you in a seaborn [`stripplot`](https://seaborn.pydata.org/generated/seaborn.stripplot.html) or [swarmplot](https://seaborn.pydata.org/generated/seaborn.swarmplot.html#seaborn.swarmplot)? – Mr. T Jan 21 '22 at 23:54
  • Thank you @Mr.T, this pickage perfectly solves my question! – Nick Nick Nick Jan 22 '22 at 03:04
  • Thank you @G.Anderson, the answer from Tirtha is a really elegant solution. Thank you for mentioning this! : D – Nick Nick Nick Jan 22 '22 at 03:05

1 Answers1

1

You can pass the x values to the c parameter in the plt.scatter function. It will use those integral values to map the colors to the points. Same integral value would mean having the same color.

import matplotlib.pyplot as plt

list1 = [1,1,1,1,2,2,2,2,3,3,3,3]
list2 = [9,8,10,11,1,2,1,2,4,5,6,7]

plt.scatter(list1, list2, c = list1)
plt.show()

enter image description here

Mayur Kr. Garg
  • 266
  • 2
  • 4
  • Thank you so much for your answer! May I ask is it possible to define the color on my own, through this method? Like 1 is red and 2 is green? – Nick Nick Nick Jan 22 '22 at 03:08
  • Yes. You can pass a list of colors into `c` as well with each value in `c` denoting a color of each point. To control color of each value of x, you can define a dictionary mapping each unique value in x to a color and then use that dict to create a list of colors for each point and pass that into `c`. – Mayur Kr. Garg Jan 22 '22 at 21:13