Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

python - pandas - scatter plot with different color legend for each point

Starting from the following example:

fig, ax = plt.subplots()

df = pd.DataFrame({'n1':[1,2,1,3], 'n2':[1,3,2,1], 'l':['a','b','c','d']})

for label in df['l']:

    df.plot('n1','n2', kind='scatter', ax=ax, s=50, linewidth=0.1, label=label)

what I obtained is the following scatterplot:

enter image description here

I'm now trying to set a different color for each of the four points. I know that I can loop over a set of, for instance, 4 colors in a list like:

colorlist = ['b','r','c','y']

but since my real dataset comprise at least 20 different points, I was looking for a sort of "color generator" to loop within it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following method will create a list of colors as long as your dataframe, and then plot a point with a label with each color:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as colors
import numpy as np
import pandas as pd

fig, ax = plt.subplots()

df = pd.DataFrame({'n1':[1,2,1,3], 'n2':[1,3,2,1], 'l':['a','b','c','d']})

colormap = cm.viridis
colorlist = [colors.rgb2hex(colormap(i)) for i in np.linspace(0, 0.9, len(df['l']))]

for i,c in enumerate(colorlist):

    x = df['n1'][i]
    y = df['n2'][i]
    l = df['l'][i]

    ax.scatter(x, y, label=l, s=50, linewidth=0.1, c=c)

ax.legend()

plt.show()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...