0

I am plotting a DataFrame as a scatter graph using this code:

My dataframe somewhat looks like this -

Sector    AvgDeg 
0        1        52
1        2        52
2        3        52
3        4        54
4        5        52
...     ...      ...

df.plot.scatter(x='Sector', y='AvgDeg', s=df['AvgDeg'], color='LightBlue',grid=True)
plt.show()

and I'm getting this result: enter image description here

What I need is to draw every dot with a different color and with the corresponding legend. For example: -blue dot- 'Sector 1', -red dot- 'Sector 2', and so on.

Do you have any idea how to do this? Tks!!

2 Answers 2

1

What you have to do is to use a list of the same size as the points in the c parameter of scatter plot.

cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
txt = ["text1", "text2", "text3", "text4"]
fig, ax = plt.subplots()
x = np.arange(1, 5)
y = np.arange(1, 5)
#c will change the colors of each point
#s is the size of each point...
#c_map is the color map you want to use 
ax.scatter(x, y,s = 40, cmap = cmap_light, c=np.arange(1, 5))
for i, j in enumerate(txt):
    #use the below code to display the text for each point
    ax.annotate(j, (x[i], y[i]))
plt.show()

What this gives you as a result is - enter image description here

To assign more different colors for 31 points for example you just gotta change the size...

ax.scatter(x, y,s = 40, cmap = cmap_light, c=np.arange(1, 32))

Similarly you can annotate those points by changing the txt list above.

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

2 Comments

Sorry @hashcode55, it's not working yet. The code works fine for 4 items, but I need to assign different colors and different legends for 31 and more items). Can you give me a hand with that please?
Great, but I already did that. I think the problem that I'm getting is that cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) only gives me a set of 3 colors, which is obvious. But I would like to see how to generate a color map with more colors.
0

i would do it this way:

import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.style.use('ggplot')

colorlist = list(mpl.colors.ColorConverter.colors.keys())

ax = df.plot.scatter(x='Sector', y='AvgDeg', s=df.AvgDeg*1.2,
                     c=(colorlist * len(df))[:len(df)])
df.apply(lambda x: ax.text(x.Sector, x.AvgDeg, 'Sector {}'.format(x.Sector)), axis=1)

plt.show()

Result

enter image description here

2 Comments

Tks for ur help but this code only works when I have a few 'sectors'. My DF has 31, so the colors are repeating themselves. How can I apply this code for 31 sectors and not repeating the colors?
@PAstudilloE, then find a way to generate a list of 31 different colors! ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.