from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
color = [str(item/255.) for item in y]
plt.scatter(x, y, s=500, c=color)
plt.show()
122
有时您可能需要 plot color precisely based on the x-value case . 例如,您可能拥有一个包含3种变量和一些数据点的数据框 . 而且你想做以下,
x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]
# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
cols=[]
for l in lst:
if l=='A':
cols.append('red')
elif l=='B':
cols.append('blue')
else:
cols.append('green')
return cols
# Create the colors list using the function above
cols=pltcolor(x)
plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()
1
无需手动设置颜色 . 而是指定灰度色彩图...
import numpy as np
import matplotlib.pyplot as plt
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()
3 回答
在matplotlib中,灰色可以作为0-1之间的数值的字符串给出 .
例如
c = '0.1'
然后,您可以将此第三个变量转换为此范围内的值,并使用它为您的点着色 .
在下面的示例中,我使用点的y位置作为确定颜色的值:
有时您可能需要 plot color precisely based on the x-value case . 例如,您可能拥有一个包含3种变量和一些数据点的数据框 . 而且你想做以下,
绘制与RED中的物理变量'A'对应的点 .
在BLUE中绘制与物理变量'B'对应的点 .
绘制对应于绿色中的物理变量'C'的点 .
在这种情况下,您可能必须写入短函数以将x值映射到相应的颜色名称作为列表,然后将该列表传递给
plt.scatter
命令 .无需手动设置颜色 . 而是指定灰度色彩图...
或者,如果您更喜欢wider range of colormaps,还可以将
cmap
kwarg指定为scatter
. 要使用其中任何一个的反转版本,只需指定其中任何一个的“_r
”版本 . 例如 .gray_r
而不是gray
. 预先制作了几种不同的灰度色标(例如gray
,gist_yarg
,binary
等) .