我有两个不同的数据集。一个是numpy NxM矩阵,另一个是Lx3 pandas数据帧。我将散点图(Lx3数据帧)叠加在等高线图(NxM)之上,并且颜色条基于散点图数据进行缩放。 如何根据两个数据集强制缩放颜色条(如何在两个图层上同步颜色条)?
import numpy as np
import matplotlib.pyplot as plt
#generate random matrix with min value of 1 and max value 5
xx = np.random.choice(a = [1,2,3,4,5],p = [1/5.]*5,size=(100,100))
#contourf plot of the xx matrix
plt.contourf(np.arange(100),np.arange(100),xx)
#generate x and y axis of the new dataframe
dfxy = np.random.choice(range(20,80),p = [1/float(len(range(20,80)))]*len(range(20,80)),size = (100,2))
#generate z values of the dataframe with min value 10 and max value 15
dfz = np.random.choice(a = np.linspace(10,15,10),p = [1/10.]*10,size = 100)
plt.scatter(dfxy[:,0],dfxy[:,1],c=dfz,s=80)
cb = plt.colorbar()
#cb.set_clim([1,15])
plt.show()
答案 0 :(得分:3)
您需要对两个图使用相同的颜色标准化。这可以通过使用matplotlib.colors.Normalize
关键字参数为两个图提供norm
实例来实现。
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
#generate random matrix with min value of 1 and max value 5
xx = np.random.choice(a = [1,2,3,4,5],p = [1/5.]*5,size=(100,100))
#generate x and y axis of the new dataframe
dfxy = np.random.choice(range(20,80),p = [1/float(len(range(20,80)))]*len(range(20,80)),size = (100,2))
#generate z values of the dataframe with min value 10 and max value 15
dfz = np.random.choice(a = np.linspace(0,7,10),size = 100)
mi = np.min((dfz.min(), xx.min()))
ma = np.max((dfz.max(), xx.max()))
norm = matplotlib.colors.Normalize(vmin=mi,vmax=ma)
plt.contourf(np.arange(100),np.arange(100),xx, norm=norm, cmap ="jet")
plt.scatter(dfxy[:,0],dfxy[:,1],c=dfz,s=80, norm=norm, cmap ="jet", edgecolor="k")
cb = plt.colorbar()
plt.show()
这两个图共享相同的颜色方案,因此可以使用单个颜色条。