Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a clean high quality GIF with fix colorbar for multiple xarray plots

I want to make a gif out of multiple plots from a xarray. I need the colorbar to be identical in all of the plots to track the change. It is easy to fix the numbers on the colorbar ticks but the color keeps changing. Somehow making GIF is messing with colors! How I can fix this?

#making GIF
fns_image=glob(save_image_dir+'/'+'*')
fns_image.sort()
with imageio.get_writer(save_gif_dir+gif_name, mode='I') as writer:
for filename in fns_image: 
    print(filename)
    image = imageio.imread(filename,)
    writer.append_data(image)

I appreciate suggestionsenter image description here.

like image 976
shimaSH Avatar asked Oct 18 '25 14:10

shimaSH


1 Answers

The 'levels' argument (as an integer) will only supply the number of levels, but always scale to the data. To set a specified range of data to be mapped, you can supply a custom array of equally spaced data. The length of the array will correspond to the number of levels.

For your case, you should change levels to levels = np.linspace(min_value, max_value, <number of levels>) instead of the range function.

EDIT with reproducible example:

import xarray as xr
import os, glob
import imageio

png_dir = '<your_directory>'
airtemps = xr.tutorial.open_dataset('air_temperature')

# Plots with variable (scaling) colorbar
for i in np.arange(25):
    plt.figure()
    plt.contourf(airtemps.air[i,:,:], levels = 25), plt.colorbar()
    plt.savefig(png_dir + 'air_temp_' + str(i) +'.png')    

max_temp = airtemps.air[:25,:,:].max()
min_temp = airtemps.air[:25,:,:].min()  

# Plots with Fixed colorbar    
for i in np.arange(25):
    plt.figure()
    plt.contourf(airtemps.air[i,:,:], levels = np.linspace(min_temp,max_temp,25)), plt.colorbar()
    plt.savefig(png_dir + 'fixed_cb_air_temp_' + str(i) +'.png')

variable_cb_images = glob.glob(png_dir + 'air*')
fixed_cb_images = glob.glob(png_dir + ('fix*'))  

var = [imageio.imread(file) for file in variable_cb_images]
fix = [imageio.imread(file) for file in fixed_cb_images]

imageio.mimsave(png_dir + '/movie_variable_cb.gif', var, fps = 10)
imageio.mimsave(png_dir + '/movie_fixed_cb.gif', fix, fps = 10)

Variable Color Bar

Fixed Color Bar

like image 157
bwc Avatar answered Oct 21 '25 03:10

bwc