【问题标题】:Plot multiple 2D gradient Data sets with colorbar. Problem: Python plots mutiple colorbar使用颜色条绘制多个 2D 渐变数据集。问题:Python 绘制多个颜色条
【发布时间】:2021-02-01 16:13:39
【问题描述】:

我正在做一些项目,我想比较我正在求解的某个方程的两个不同解。 我有一些时间和空间(x,y)相关的数据。这意味着我对于每个时间步 T 都有一个数据文件 T.dat,其中包含我正在求解的方程的 x y 和 Z 值。 当我单独绘制方程的解时,一切正常。 一旦我尝试创建一个循环来迭代一些时间步骤,我就会遇到我的颜色条在第二次迭代中没有被删除的问题。对于第一个情节,它工作正常,但在第二个情节之后,Colorbars 不断在情节中添加。

看起来就是这样。

经过四次迭代

这是我的代码示例。 首先我导入了我的库。

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

其次,我开始在 Dataframes 中导入我的数据(一些细节是我的更改,但它与我的问题无关)(请注意,路径几乎都是相同的,因为我想先测试绘图功能。如果这可行,我会把它的数据)

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)

到目前为止一切顺利。现在这是我如何定义我的绘图功能,这就是我认为问题开始发生的地方。我认为我的问题在于我如何在函数中定义颜色条。

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()

现在,如果我想绘制我的数据,这就是我所做的。我刚刚做了一个for循环。

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")
   
   

所以。我试图在循环结束时使用 plt.clf() Fig.clf() plt.close() 。 我的想法是 Python 不会删除以前的颜色条,这就是为什么我试图告诉 python 他应该在每次绘图后清除数字,它的作用是我只是完全删除数字并且我得到两个空白图。 像这样 [plt.clf() 之后的绘图] 然后我想也许我可以用 Ax1.cla() 清除轴,这也没有用。

提前感谢您的帮助。 我为我的物理学家意大利面条代码道歉。

你好,齐诺

【问题讨论】:

标签: python plot gradient figure colorbar


【解决方案1】:

我解决了我的问题。

基本上问题在于我如何定义 Plot 函数。

 def plotgradient_double(fig,ax1,ax2,X,Y,Z1,Z2 ,title1, title2 ):
    nbins= params_Values[1] #this creats t'he gridpoints
    axes= [ax1,ax2]
    xi, yi = np.mgrid[X.values.min():X.values.max():nbins*1j, Y.values.min():Y.values.max():nbins*1j] #rearange the arrays 
    #datas you need 
    t1= ax1.pcolormesh(xi, yi, Z1.values.reshape(int(nbins),int(nbins)), cmap='jet',vmax=1.) 
    t2= ax2.pcolormesh(xi, yi, Z2.values.reshape(int(nbins),int(nbins)), cmap='jet',vmin=0,vmax=1. )      #plottingfunction
    #CS1=ax1.contour(xi, yi, Z1.values.reshape(int(nbins),int(nbins)) )
    #CS2=ax2.contour(xi, yi, Z2.values.reshape(int(nbins),int(nbins)) )
    #ax1.clabel(CS1, inline=1, fontsize=10)
    #ax2.clabel(CS2, inline=1, fontsize=10)
    #colorbar=fig.colorbar(T, ax=axc, shrink=0.5, aspect=5)
    for ax in axes:
        ax.set_xlabel('x',fontsize=15) #labels
        ax.set_ylabel('y',fontsize=15)  
         #title
        #ax.grid()
    ax1.set_title(title1,fontsize=15)
    ax2.set_title(title2,fontsize=15) 
    return t1,t2

之后我可以在 for 循环中创建一个颜色条来绘制多个数据并在每次迭代后将其删除。

colorbar.remove()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2014-08-23
    • 2017-07-12
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多