Skip to main content
 首页 » 编程设计

python之matplotlib 散点图颜色作为第三和第四变量的函数

2024年10月24日13jillzhang

有没有什么方法可以使用两个变量设置颜色来为散点图着色? IE。 a 设置蓝色级别,b 设置红色级别?类似这样的事情:

import pylab 
import numpy 
x = numpy.random.random(50) 
y = numpy.random.random(50) 
a = numpy.random.random(50) 
b = numpy.random.random(50) 
s = pylab.scatter(x,y,c='red' * a + 'blue'*b) 
pylab.colorbar(s) 
pylab.show() 

请您参考如下方法:

扩展 faltru 的答案,您可以使用 imshow 制作二维颜色条:

import numpy as np 
from matplotlib import pyplot as plt 
x = np.random.random(50) 
y = np.random.random(50) 
a = np.random.random(50) 
b = np.random.random(50) 
s = c=zip(a, b, np.zeros(50)) 
ax = plt.gca() 
print ax.get_position() 
plt.scatter(x,y,c = s) 
#adjust limits to make room for inset axes 
plt.xlim(xmax = 1.5) 
plt.ylim(ymax = 1.5) 
#create inset axes 
ax = plt.axes([.7, .675, .2, .2], axisbg='y') 
n = 20 
red = np.linspace(min(a), max(a), n) 
green = np.linspace(min(b), max(b), n) 
floats = np.linspace(0, 1, n) 
#make arrays of all possible values between 0 and 1 
X, Y = np.meshgrid(floats, floats) 
#stack the arrays with a third array of zeros 
Z = np.dstack((X, Y, np.zeros(X.shape))) 
Z = np.rot90(Z) 
red = np.round(red[::-1], 2) 
green = np.round(green, 2) 
plt.imshow(Z) 
ticks = np.arange(0, n, 6) 
plt.yticks(ticks, [red[i] for i in ticks]) 
plt.xticks(ticks, [green[i] for i in ticks], rotation = 'vertical') 
plt.xlabel('Green') 
plt.ylabel('Red') 
plt.show()