python pyplot: colorbar on contourf and scatter in same plot

僤鯓⒐⒋嵵緔 提交于 2020-08-22 06:56:47

问题


I have two different datasets. One is a numpy NxM matrix and another is a Lx3 pandas dataframe. I am overlaying scatter plot (Lx3 dataframe) on top of a contour plot (NxM) and the colorbar is scaling based on the scatter plot data. How can I force the colorbar to scale based on both data sets (How can I synchronize the colorbar on both plot layers)?

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()

I trie to set limits but the results still don't make sense to me. The contourf still doesn't seem to be represented in the colorbar.


回答1:


You need to use the same color normalization for both plots. This can be accomplished by providing a matplotlib.colors.Normalize instance to both plots using the norm keyword argument.

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()

Here both plots share the same color scheme and so a single colorbar can be used.



来源:https://stackoverflow.com/questions/42228113/python-pyplot-colorbar-on-contourf-and-scatter-in-same-plot

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