简体   繁体   中英

Set the color for scatter-plot with DataFrame.plot

I am using python to plot a pandas DataFrame

I set the color for plotting like this:

allDf = pd.DataFrame({
    'x':[0,1,2,4,7,6],
    'y':[0,3,2,4,5,7],
    'a':[1,1,1,0,0,0],
    'c':['red','green','blue','red','green','blue']
},index = ['p1','p2','p3','p4','p5','p6'])

allDf.plot(kind='scatter',x='x',y='y',c='c')
plt.show()

However it doesn't work (every point has a blue color)

If I changed the definition of DataFrame like this

'c':[1,2,1,2,1,2]

It appears color but only black and white, I want to use blue, red and more...

Replace it by:

allDf.plot(kind='scatter',x='x',y='y',c=allDf.c)

Output:

在此处输入图片说明

The c argument of pandas.DataFrame.plot is in this case passed through literally so everything will have the color 'c' (cyan) .

You need to pass your column directly:

allDf.plot(kind='scatter', x='x', y='y', c=allDf['c'])

在此处输入图片说明

It's a bit weird and not well documented when the c parameter will use the column and when it will use the literal value. So in this case it's probably best to provide the "colors" explicitly. You might want to take a look at the source code in case you're interested to debug what is happening there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM