Matplotlib Scatter plot change color based on value on list

本秂侑毒 提交于 2019-12-12 07:07:13

问题


I'm quite new to matplotlib and i would like to know how we can change color of points on a scatter plot based on the value in a list.

In fact, I have a 2-D array that I want to plot and a list with the same number of rows containing, for each point, the color we want to use.

#Example
data = np.array([4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582])
colors = ['red','red','red','blue','red','blue']
ax1.plot(data[:,0],data[:,1],'o',picker=True)

How to set the color parameter to fit my list of colors ?


回答1:


Using a line plot plt.plot()

plt.plot() does only allow for a single color. So you may simply loop over the data and colors and plot each point individually.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
data = np.array([[4.29488806,-5.34487081],
                [3.63116248,-2.48616998],
                [-0.56023222,-5.89586997],
                [-0.51538502,-2.62569576],
                [-4.08561754,-4.2870525 ],
                [-0.80869722,10.12529582]])
colors = ['red','red','red','blue','red','blue']
for xy, color in zip(data, colors):
    ax.plot(xy[0],xy[1],'o',color=color, picker=True)

plt.show()

Using scatter plot plt.scatter()

In order to produce a scatter plot, use scatter. This has an argument c, which allows numerous ways of setting the colors of the scatter points.

(a) One easy way is to supply a list of colors.

colors = ['red','red','red','blue','red','blue']
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", picker=True)

(b) Another option is to supply a list of data and map the data to color using a colormap

colors = [0,0,0,1,0,1] #red is 0, blue is 1
ax.scatter(data[:,0],data[:,1],c=colors,marker="o", cmap="bwr_r")



回答2:


You have to set argument c of plt.scatter with a list of desired colors:

import matplotlib.pylab as plt
import numpy as np

data = np.array([[4.29488806,-5.34487081],
[3.63116248,-2.48616998],
[-0.56023222,-5.89586997],
[-0.51538502,-2.62569576],
[-4.08561754,-4.2870525 ],
[-0.80869722,10.12529582]])

colors = ['red','red','red','blue','red','blue']
plt.scatter(data[:,0],data[:,1],marker='o',c = colors)
plt.show()



来源:https://stackoverflow.com/questions/43090817/matplotlib-scatter-plot-change-color-based-on-value-on-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!