Matplotlib散点图根据列表上的值更改颜色 [英] Matplotlib Scatter plot change color based on value on list
问题描述
我对matplotlib还是很陌生,我想知道我们如何根据列表中的值更改散点图上点的颜色.
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)
如何设置color参数以适合我的颜色列表?
How to set the color parameter to fit my list of colors ?
推荐答案
使用折线图plt.plot()
plt.plot()
仅允许使用一种颜色.因此,您可以简单地遍历数据和颜色并分别绘制每个点.
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()
使用散点图plt.scatter()
为了生成散点图,请使用scatter
.它具有参数c
,该参数允许使用多种方式设置散点的颜色.
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)一种简单的方法是提供颜色列表.
(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)另一个选择是提供数据列表,并使用颜色图将数据映射为颜色
(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")
这篇关于Matplotlib散点图根据列表上的值更改颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!