简体   繁体   中英

How to fix the limits of color scale in matplotlib?

I am implementing a loop to produce contour plots using the function contourf in matplotlib. The objective of the study is to find out any moving patterns in the area. But, the plots produced are having different color scales. Some of them have -4 to 4 while others have -1.5 to 9.0 and so on which renders the interpretation pointless. How can I fix this color scale to -5.0 to 9.0?

Also, when I try to export the plots number of colorbars increases in each plot. For example the second plot in the loop has 2 colorbars and fifth plot has 5 colorbars and so on.

What I've done so far:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from numpy import linspace
from numpy import meshgrid

i=0
while i<len(inputdata):
    map = Basemap(projection='cyl', llcrnrlat=5.125, llcrnrlon=60.125, urcrnrlat=34.875, urcrnrlon=94.875)

    data = np.array(inputdata[i])

    x = linspace(map.llcrnrx, map.urcrnrx, data.shape[1])
    y = linspace(map.llcrnry, map.urcrnry, data.shape[0])

    xx, yy = meshgrid(x, y)

    map.contourf(xx, yy, data, cmap = 'summer_r')

    plt.colormap()
    plt.savefig('filename.jpg',dpi=300)
    i+=1

In order to change the limits of the colorbar, you can call plt.clim() before you call plt.colorbar and specify the range manually:

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from numpy import linspace
from numpy import meshgrid

i=0
while i<len(inputdata):
    map = Basemap(projection='cyl', llcrnrlat=5.125, llcrnrlon=60.125, urcrnrlat=34.875, urcrnrlon=94.875)

    data = np.array(inputdata[i])

    x = linspace(map.llcrnrx, map.urcrnrx, data.shape[1])
    y = linspace(map.llcrnry, map.urcrnry, data.shape[0])

    xx, yy = meshgrid(x, y)

    map.contourf(xx, yy, data, cmap = 'summer_r')

    plt.clim(-5, 9)  # manually setup the range of the colorscale and colorbar
    plt.colormap()
    plt.savefig('filename.jpg',dpi=300)
    plt.clf()
    i+=1

You also may want to clear the figure after you have saved it to avoid multiple colorbars appearing using plt.clf()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM