python中plt.imshow,Python:如何将plt.imshow()嵌套在For循环中?

from__future__importdivision#Avoids the floor of the mathematical result of division if the args are ints or longsimportnumpyasnpimportmatplotlib.pyplotaspltimportmatplotlib.colorsasmcimportSSFM2Dimportrandom#Parameter assignmentsmax_level=8#This is the exponent controlling the grid size. In this case N=2^8=256. Use only integers.N=2**max_level

sigma=1#Variation for random Gauss generation (standardised normal distribution)H=0.8#Hurst exponent (0.8 is a recommended value for natural phenomena)seed=random.random()#Setting the seed for random Gauss generationprint('The lattice size is '+str(N)+'x'+str(N))#Lattice initializationLattice=np.zeros((256,256))#Calling Spectral fBm functionLattice=SSFM2D.SpectralSynthesisFM2D(max_level,sigma,H,seed,normalise=True,bounds=[0,1])#Plotting the original 256x256 latticeM=np.zeros((257,257))foriinrange(0,256):forjinrange(0,256):M[i][j]=Lattice[i][j]#Normalizing the output matrixprint('Original sum: '+str(round(M[-257:,-257:].sum(),3)))M=M/M[-257:,-257:].max()#Matrix normalization with respect to max#Lattice statisticsprint('Normalized sum: '+str(round(M[-257:,-257:].sum(),3)))print('Normalized max: '+str(round(M[-257:,-257:].max(),3)))print('Normalized min: '+str(round(M[-257:,-257:].min(),3)))print('Normalized avg: '+str(round(M[-257:,-257:].mean(),3)))#Determining the footprintfootprint=0#Initializing the footprint count variableforiinrange(M.shape[0]):forjinrange(M.shape[1]):ifM[i][j]>0.15:# Change here to set the failure thresholdfootprint=footprint+1print('Event footprint: '+str(round(footprint*100/(256*256),2))+'%')#Plotting the 256x256 "mother" matrixplt.imshow(M[-257:,-257:].T,origin='lower',interpolation='nearest',cmap='Reds',norm=mc.Normalize(vmin=0,vmax=M.max()))title_string=('Spatial Loading of a Generic Natural Hazard')subtitle_string=('Inverse FFT on Spectral Synthesis')plt.suptitle(title_string,y=0.99,fontsize=17)plt.title(subtitle_string,fontsize=8)plt.show()#Making a custom list of tick mark intervals for color bar (assumes minimum is always zero)numberOfTicks=5ticksListIncrement=M.max()/(numberOfTicks)ticksList=[]foriinrange((numberOfTicks+1)):ticksList.append(ticksListIncrement*i)plt.tick_params(axis='x',labelsize=8)plt.tick_params(axis='y',labelsize=8)cb=plt.colorbar(orientation='horizontal',format='%0.2f',ticks=ticksList)cb.ax.tick_params(labelsize=8)cb.set_label('Loading',fontsize=12)plt.show()plt.xlim(0,255)plt.xlabel('Easting (Cells)',fontsize=12)plt.ylim(255,0)plt.ylabel('Northing (Cells)',fontsize=12)plt.annotate('fractional Brownian motion on a 256x256 lattice | H=0.8 | Dim(f)= '+str(3-H),xy=(0.5,0),xycoords=('axes fraction','figure fraction'),xytext=(0,0.5),textcoords='offset points',size=10,ha='center',va='bottom')plt.annotate('Max: '+str(round(M[-257:,-257:].max(),3))+' | Min: '+str(round(M[-257:,-257:].min(),3))+' | Avg: '+str(round(M[-257:,-257:].mean(),3))+' | Footprint: '+str(round(footprint*100/(256*256),2))+'%',xy=(0.5,0),xycoords=('axes fraction','figure fraction'),xytext=(0,15),textcoords='offset points',size=10,ha='center',va='bottom')#Producing the 101x101 image(s)numfig=int(raw_input('Insert the number of 101x101 windows to produce: '))N=np.zeros((101,101))x=0#Counts the iterations towards the chosen number of imagesforxinrange(1,numfig+1):print('Image no. '+str(x)+' of '+str(numfig))north=int(raw_input('Northing coordinate (0 thru 155, integer): '))east=int(raw_input('Easting coordinate (0 thru 155, integer): '))foriinrange(101):forjinrange(101):N[i][j]=M[north+i][east+j]#Writing X, Y and values to a .csv file from scratchimportnumpyimportcsvwithopen('C:\\Users\\Francesco\\Desktop\\Python_files\\csv\\fBm_101x101_'+str(x)+'of'+str(numfig)+'.csv','w')asf:#Change directory if necessarywriter=csv.writer(f)writer.writerow(['X','Y','Value'])for(x,y),valinnumpy.ndenumerate(M):writer.writerow([x,y,val])#Plotting the 101x101 "offspring" matricesplt.imshow(N[-101:,-101:].T,origin='lower',interpolation='nearest',cmap='Reds',norm=mc.Normalize(vmin=0,vmax=M.max()))title_string=('Spatial Loading of a Generic Natural Hazard')subtitle_string=('Inverse FFT on Spectral Synthesis | Origin in the 256x256 matrix: '+str(east)+' East; '+str(north)+' North')plt.suptitle(title_string,y=0.99,fontsize=17)plt.title(subtitle_string,fontsize=8)plt.show()#Making a custom list of tick mark intervals for color bar (assumes minimum is always zero)numberOfTicks=5ticksListIncrement=M.max()/(numberOfTicks)ticksList=[]foriinrange((numberOfTicks+1)):ticksList.append(ticksListIncrement*i)plt.tick_params(axis='x',labelsize=8)plt.tick_params(axis='y',labelsize=8)cb=plt.colorbar(orientation='horizontal',format='%0.2f',ticks=ticksList)cb.ax.tick_params(labelsize=8)cb.set_label('Loading',fontsize=12)plt.show()plt.xlim(0,100)plt.xlabel('Easting (Cells)',fontsize=12)plt.ylim(100,0)plt.ylabel('Northing (Cells)',fontsize=12)plt.annotate('fractional Brownian motion on a 101x101 lattice | H=0.8 | Dim(f)= '+str(3-H),xy=(0.5,0),xycoords=('axes fraction','figure fraction'),xytext=(0,0.5),textcoords='offset points',size=10,ha='center',va='bottom')plt.annotate('Max: '+str(round(N[-101:,-101:].max(),3))+' | Min: '+str(round(N[-101:,-101:].min(),3))+' | Avg: '+str(round(N[-101:,-101:].mean(),3))+' | Footprint: '+str(round(footprint*100/(101*101),2))+'%',xy=(0.5,0),xycoords=('axes fraction','figure fraction'),xytext=(0,15),textcoords='offset points',size=10,ha='center',va='bottom')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
### 回答1: plt.imshow是matplotlib库的一个函数,用于显示图像。它可以将一个二维数组或三维数组的数据转换成图像,并在屏幕上显示出来。在使用plt.imshow函数时,需要传入一个数组作为参数,该数组可以是灰度图像、RGB图像或其他类型的图像。同时,还可以设置图像的颜色映射、坐标轴、标题等属性。 ### 回答2: plt.imshow是matplotlib.pyplot的函数,主要用于绘制图像。该函数的基本用法是以二维数组的形式传递给它,并将这个二维数组表示的图像绘制出来。下面对plt.imshow的用法进行介绍。 plt.imshow(arr, cmap=None, aspect=None, interpolation=None) 参数说明: - arr:表示绘制的二维数组; - cmap:表示使用的颜色图谱; - aspect:表示绘制图像时x和y轴的比例; - interpolation:表示绘制图像时采用的插值方法。 使用plt.imshow绘制图像时,需要对绘制时的像素数组进行一些格式化,主要有以下几种方式: 1. 将像素数组压缩,通常该方式适用于像素数组非常大的情况: compressed_pixels = compress_pixels(pixels) plt.imshow(compressed_pixels) 2. 对像素数组进行旋转,通常该方式适用于实际处理的图像本身就需要进行旋转: rotated_pixels = rotate_pixels(pixels) plt.imshow(rotated_pixels) 3. 对像素数组进行缩放,通常该方式适用于需要对图像进行缩放以适应特定的显示区域: scaled_pixels = scale_pixels(pixels) plt.imshow(scaled_pixels) 4. 对像素数组进行裁剪,通常该方式适用于需要将图像的某个部分进行放大或缩小: cropped_pixels = crop_pixels(pixels) plt.imshow(cropped_pixels) 5. 对像素数组进行滤波,通常该方式适用于需要对图像进行降噪或平滑处理: filtered_pixels = filter_pixels(pixels) plt.imshow(filtered_pixels) 在使用plt.imshow绘制图像时,可以通过设置不同的参数,来自定义生成的图像的外观和特性。其常用的一些参数是: a. cmap:指定使用的色图。常见的色图有"gray"、"hot"、"cool"、"spring"、"summer"、"autumn"、"winter"、"bone"等等。 b. interpolation:指定绘制图像时采用的插值方法,通常有“nearest”、”bilinear”、”bicubic”、”spline16”、”spline36”、”hanning”、”hamming”等方法。 c. aspect:指定绘制图像时x轴和y轴的比例。可以设置为auto、equal或具体数值。 在绘制完图像后,还可以使用plt.colorbar()方法添加色度条。 总之,plt.imshow是matplotlib.pyplot的非常常用的函数,可以用于显示和处理图像,定制图像外观和特性。希望本篇回答能够帮助到读者们。 ### 回答3: Python的matplotlib库是一个非常强大的数据可视化库,它提供了非常丰富的绘图功能。matplotlib的pyplot子库提供了大量的绘图API,其plt.imshow()函数用于在二维图形界面展示图片。 plt.imshow()的基本语法如下: plt.imshow(X, cmap=None) 其,X表示要绘制的图像,cmap参数表示使用的颜色映射表。 当X是一个二维数组时,imshow函数会将数据矩阵的每个元素值作为一个像素的亮度值来绘制图像,形成灰度图。如果X是一个三维矩阵,则可以使用cmap参数设置颜色映射表,实现彩色图像的绘制。 除了基本语法外,imshow函数还有许多其他的参数,用于进一步定制可视化效果。例如: aspect:设置图像的长宽比。 interpolation:设置图像插值方式,即如何处理图像像素之间的空隙,比如设置为nearest表示使用最近邻插值。 vmin,vmax:设置图像像素值的范围,如果不设置,则默认使用数据的最小值和最大值。 origin:设置图像的坐标原点,比如设置为lower表示使用左下角坐标原点。 plt.imshow()函数是数据可视化过程非常常用的函数之一,它可以帮助我们快速的绘制出一张图像,以展示我们的数据。在数据分析过程,我们可以使用plt.imshow()函数将数据的信息提取出来并以可视化的方式展示,从而帮助我们更好地理解数据,发掘其的规律和特征。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值