One color bar for multiple scatter plots

I draw several shapes of the same variable on the same chart using the matplotlib library. I am not looking for a colorbar for subtitles , which is the dominant search material. I draw a few scatter s, but the colorbar is only set to the values ​​of the last scatter I.

Here is the piece of code:

 plt.scatter(x1, y1, c=z1,cmap='viridis_r',marker='s') plt.scatter(x2, y2, c=z2,cmap='viridis_r',marker='o') plt.scatter(x3, y3, c=z3,cmap='viridis_r',marker='^') plt.colorbar().set_label('Wind speed',rotation=270) 
+5
source share
2 answers

It takes a little extra work:

  • You should get the minimum and maximum c (color scale values)
  • You have to clim every scatter plot

First minimum and maximum:

 zs = np.concatenate([z1, z2, z3], axis=0) min_, max_ = zs.min(), zs.max() 

Then scatter plots with clim :

 plt.scatter(x1, y1, c=z1,cmap='viridis_r',marker='s') plt.clim(min_, max_) plt.scatter(x2, y2, c=z2,cmap='viridis_r',marker='o') plt.clim(min_, max_) plt.scatter(x3, y3, c=z3,cmap='viridis_r',marker='^') plt.clim(min_, max_) plt.colorbar().set_label('Wind speed',rotation=270) 

For a very simple data set:

 x1, x2, x3 = [1,2,3], [2,3,4], [3,4,5] y1 = y2 = y3 = [1, 2, 3] z1, z2, z3 = [1,2,3], [4,5,6], [7,8,9] 

enter image description here

+2
source

scatter has an argument of norm . Using the same norm for all diffusers ensures that the color bar created by any of the graphs (and therefore the last one) is the same for all scatter plots.

norm can be an instance of Normalize , to which the minimum and maximum values ​​are set, and which creates a linear scaling between them. Of course, you can also use any other norm provided in matplotlib.colors , for example PowerNorm , LogNorm , etc.

 mini, maxi = 0, 2 # or use different method to determine the minimum and maximum to use norm = plt.Normalize(mini, maxi) plt.scatter(x1, y1, c=z1,cmap='viridis_r',marker='s', norm=norm) plt.scatter(x2, y2, c=z2,cmap='viridis_r',marker='o', norm=norm) plt.scatter(x3, y3, c=z3,cmap='viridis_r',marker='^', norm=norm) plt.colorbar().set_label('Wind speed',rotation=270) 
0
source

Source: https://habr.com/ru/post/1271623/


All Articles