1

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. enter image description here

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.