Question

I made an animation of a wave, but the colorbar keeps shifting around, and I don't know why. I think it is because it normalises after each frame. How can I set the the colormap setting so the colorbar stays the same?

Code: WARNING: this prgramm deletes the folder png3D in the directory it is called. It also can take a while for all frames to be made, depending on your computational power.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import time
import sys,os,shutil
time.clock()

def FUNCTION(p,r,t):
    k_0,dx,c = p
    x,y = r
    x,y = np.meshgrid(x,y)
    r = np.sqrt(x**2 + y**2)
    z = np.exp(1j*(k_0[0]*x+k_0[1]*y-c*t))*np.exp(-((r-c*t)/(2*dx))**2 )*0.5**(r/x[0][-1]/2)
    z = abs(z)
    return(x,y,z)

def PRINT_PNG(x,y,t,folder):
    x,y,z = FUNCTION(p,r,t)

    fig = plt.figure()
    sub = fig.gca(projection='3d')
    fig.suptitle("3D Wavepackage", size="large")
    sub.set_zlim([0,1.5])
    sub.set_xlabel("x",size="large")
    sub.set_ylabel("y",size="large")
    sub.set_zlabel("$Re[\psi(x,t)]$",size="large",ha="right")   
    sub.text(0.5,0.5,0.5,"t = "+str("%3.1f"%t)+" s",transform = sub.transAxes, ha="right")

    surf = sub.plot_surface(x,y,z,linewidth=0,cmap=cm.coolwarm)
    fig.colorbar(surf, shrink=0.5, aspect=5)
    file_name = os.path.abspath(folder+"/tmp"+str("%04d"%i)+".png")
    fig.savefig(file_name)
    plt.close()

# Parameters
T = 10
N = 100
n = 24*T # 24 Frames pro Sekunde
t = np.linspace(0,T,n)
k_0 = [1,1]
dx  = 1
c   = 1
p = [k_0,dx,c]

x   = np.linspace(-c*T,c*T,N)
y   = np.linspace(-c*T,c*T,N)
r=[x,y]


# Baue Ordner
folder = os.path.abspath("png3D")
if os.path.exists(folder)==True:
    shutil.rmtree(folder)
    os.makedirs(folder)
else:
    os.makedirs(folder)

for i in range(n):
    PRINT_PNG(x,y,t[i],folder)
    print(str(i+1)+"/"+str(n))

file_name = os.path.abspath("png3D//tmp%04d.png")
os.system("ffmpeg -f image2 -y -i "+file_name+" -r 24 -bit_rate 1800 3D_Wave.mpeg")
shutil.rmtree(folder)
print(time.clock())
Was it helpful?

Solution

You can pass vmin and vmax keyword arguments to plot_surface that specify the value range for your plot:

surf = sub.plot_surface(x,y,z,linewidth=0,cmap=cm.coolwarm,vmin=0,vmax=1)

See the docs for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top