I am working on some project where I want to compare two different solution of some equation I am solving. I have some data that are time and Space (x,y) dependent. which means I have for every time step T a data file T.dat which contains the x y and Z values of my equation I am solving. When I plot the solutions of the equation individually everything works fine. as soon as i try to make a loop to iterate over some time steps I get the problem that my Color bar doesn't get remove in the second iteration. for the first Plot it works fine but after the second one Colorbars keeps adding up in the plot.
thats how it looks like.
After four Itteration
Here is a Sample of my Code. First I imported my Libraries.
import numpy as np
import glob
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import animation
import scipy as sp
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('jpg')
from mpl_toolkits.mplot3d import Axes3D
#%matplotlib qt
import animatplot as amp
from sklearn.preprocessing import StandardScaler
Secondly I start Importing my Datas in Dataframes (Some specifics my change but it is not relevant for my problem) (Note that the Path are mostly all the same because i wanted to test the plot function first. if this works I will put the Datas for it )
path_nonoise = r'Thesis/NCKSM/FieldData/'
path_noise_additive = r'Thesis/NCKSM/FieldData/'
path_noise_multiplicative = r'Thesis/NCKSM/FieldData/'
path_params_nonoise = r'Thesis/NCKSM/ParameterData/'
path_params_additive = r'Thesis/NCKSM/ParameterData/'
path_params_multiplicative= r'Thesis/NCKSM/ParameterData/'
all_files = len( sorted (glob.glob(path_nonoise + "/*.dat"))) #patern for the files
params_nonoise= pd.read_table(path_params_nonoise+'0'+'.dat',sep=':',names=['Params', 'Value',] )
params_Names_nonoise= np.asarray(params_nonoise['Params'].values.tolist())
params_Values_nonoise= np.asarray(params_nonoise['Value'].values.tolist())
quantum= int(params_Values_nonoise[3])
numberofdatas = np.arange(0,all_files)
#creat a list of the names
timesteps = np.arange(0,all_files*quantum,quantum )
nameofdata = [str(timesteps) for timesteps in timesteps]
# use your path
dfs_nonoise=[]
dfs_noise_additive=[]
dfs_noise_multiplicative=[]
for filename in nameofdata:
foo1=pd.read_table(path_nonoise+filename+'.dat',sep='\s+',names=['X', 'Y','C','Rho'] )
foo2=pd.read_table(path_noise_additive+filename+'.dat',sep='\s+',names=['X', 'Y','C','Rho'] )
foo3=pd.read_table(path_noise_multiplicative+filename+'.dat',sep='\s+',names=['X', 'Y','C','Rho'] )
dfs_nonoise.append(foo1)
dfs_noise_additive.append(foo2)
dfs_noise_multiplicative.append(foo3)
so far so good. Now here is how i defined my Ploting function and that's where I think the problems starts to occur. I Think that my Problemes lies in how i defined my colorbar in the function.
def plotgradient(fig,ax,X,Y,Z ,title ):
nbins= params_Values_nonoise[1] #this creats the gridpoints
X_0= np.asarray(X.values.tolist())
Y_0= np.asarray(Y.values.tolist())
xi, yi = np.mgrid[X_0.min():X_0.max():nbins*1j, Y_0.min():Y_0.max():nbins*1j] #rearange the arrays
zi = np.asarray(Z.values.tolist()) #datas you need
t= ax.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap='jet') #plottingfunction
CS=ax.contour(xi, yi, zi.reshape(xi.shape) )
ax.clabel(CS, inline=1, fontsize=10)
colorbar=plt.colorbar(t, ax=ax, shrink=0.5, aspect=5) # colorbar
ax.set_xlabel('x') #labels
ax.set_ylabel('y')
ax.set_title(title) #title
ax.grid()
now if i want to plot my datas thats what i have done. i just made a for Loop.
Fig, axes = plt.subplots(ncols=2,nrows=1,figsize=(20,15))
my_path=r'/home/belkadi/Thesis/Plots/Plots27.01/additiveandnonoise/'
Ax1,Ax2=axes.flatten()
test=[0,1,2,3,4,5]
for i,j in zip(test,nameofdata[0:5]):
f1=plotgradient(Fig, Ax1,dfs_nonoise[i]['X'],dfs_nonoise[i]['Y'], dfs_nonoise[i]['Rho'],'Density Gradient without noise' )
f2=plotgradient(Fig, Ax2,dfs_nonoise[i]['X'],dfs_nonoise[i]['Y'], dfs_nonoise[i]['Rho'],'Density with noise' )
plt.savefig(my_path+j+".png")
So. I have tried to use plt.clf() Fig.clf() plt.close() at the end of the loop.
My idea was that Python doesn't delete the previous colourbar and thats why I tried to tell python he should clear clear the figure after every plot what it does is that i just delets the figure completly and i get two blank plot.
Like this [Plots after plt.clf()]
then i thought maybe i could clear the axis with Ax1.cla() this also didnt work.
thanks in advance for the help. And i apologize for my physicist spaghetti code.
Greetings Zino