matplotlib colorbar

  1. 引用

    cf=ax.contourf(... ...)
    fig.colorbar(cf)
  2. 参数  ax 

    # 把色卡放到 ax2 子图旁边
    fig.colorbar(acf1,ax=ax2)
  3. 参数 extend

    # 色条展示尖角的参数extend,他可以使色条展现出角的形状,其可选命令both表示两头都变尖,max表示数值大的那头变尖,min表示小的那头变尖。
    cf=ax.contourf(x,y,z,extend='both')
    fig.colorbar(cf,extend='both')
  4. 参数 shrink

    # 缩放参数shrink,从0-1,色条将会按照输入值被缩放
    cf=ax.contourf(x,y,z)
    fig.colorbar(cf,shrink=0.5)
  5. 参数 pad

    # 控制色条与子图的间距
    fig.colorbar(cf,pad=0.005)
  6. 参数 orientation

    # 控制色条时横纵方向,当为horizontal时,色条将被平放在下方,默认在右边
    fig.colorbar(cf,orientation='horizontal')
  7. 参数 ticks

    # 传入一个列表,显示你想展示的刻度,其他刻度将消失。类似于ax.set_yticks( ).
    fig.colorbar(cf,ticks=[0,2,4,16])
  8. 参数 format

    # 控制色条上刻度的格式,比如将其保留两位小数
    fig.colorbar(cf,format='%.2f')
  9. 参数 label

    # 简单的给色条一个标签
    fig.colorbar(cf,label='色条')
  10. 参数 

    cf=ax.contourf(x,y,z)
    fc=fig.colorbar(cf)
    #使用fc省称
    ax2=fc.ax
    #调出colorbar的ax属性
    ax2.set_title('这是色条的标题',fontsize=5)
    ax2.tick_params(which='major',direction='in',labelsize=4,length=7.5)
    ax2.tick_params(which='minor',direction='in')
    ax2.yaxis.set_minor_locator(mticker.MultipleLocator(0.5))
    #显示x轴副刻度 
  11. 双刻度值

    import numpy as np
    from matplotlib.colors 
    import Normalize
    import matplotlib as mpl
    import pandas as pd
    import cartopy.crs as ccrs
    import cartopy.feature as cfeat
    from cartopy.mpl.gridliner
    import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    from cartopy.io.shapereader import Reader
    from scipy.interpolate import Rbf
    import matplotlib.pyplot as plt
    import matplotlib.ticker as mtickerimport 
    syssys.path.append(r"C:\Users\lenovo\Desktop")import maskoutplt.rcParams['font.sans-serif']=['SimHei']
    extent=[108.2,110.8,29.1,31.401]
    proj= ccrs.PlateCarree() 
    fig = plt.figure(figsize=(7, 10),dpi=500)  
    ax = fig.subplots(1, 1, subplot_kw={'projection': proj})  
    reader = Reader(r'E:\家园\区划-省界\恩施.shp')
    cities = cfeat.ShapelyFeature(reader.geometries(), proj, edgecolor='k', facecolor='none')
    ax.add_feature(cities, linewidth=0.7)
    ax.set_extent(extent, crs=proj)gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,linewidth=0.7, color='k', alpha=0.5, linestyle='--')
    gl.xlabels_top = False 
    gl.ylabels_right = False 
    gl.xformatter = LONGITUDE_FORMATTER 
    gl.yformatter = LATITUDE_FORMATTER 
    gl.xlocator = mticker.FixedLocator(np.arange(extent[0],extent[1]+0.5, 0.4))
    gl.ylocator = mticker.FixedLocator(np.arange(extent[2],extent[3]+0.5, 0.4))
    gl.xlabel_style={'size':10}gl.ylabel_style={'size':10}    ###############################以下为添加县市名称和点########################################nameandstation={"恩施":[109.5,30.2],"利川":[109,30.3],"巴东":[110.34,31.04],"建始":[109.72,30.6],"宣恩":[109.49,29.987],"来凤":[109.407,29.493],"咸丰":[109.14,29.665],"鹤峰":[110.034,29.89]}for key,value in nameandstation.items():    ax.scatter(value[0] , value[1] , marker='.' , s=90 , color = "k" , zorder = 3)    ax.text(value[0]-0.07 , value[1]+0.03 , key , fontsize = 12 , color = "k")    ##############################################读取文件打包数据###########################################filename=r'C:\Users\lenovo\Desktop\累年降水数据.xlsx'#数据文件地址,这个数据是我捏造的,没有实际意义df=pd.read_excel(filename)#读取文件lon=df['lon']#读取站点经度lat=df['lat']#读取站点纬度rain=df['precipitation']#读取站点累计年降水量olon=np.linspace(108,111,30)#设置网格经度olat=np.linspace(29,32,30)#设置网格纬度olon,olat=np.meshgrid(olon,olat)#网格化func=Rbf(lon,lat,rain,function='linear')#定义插值函数rain_new=func(olon,olat)#获得插值后的网格累计降水量cs= ax.contourf(olon,olat,rain_new,levels=np.arange(900,2000,100),cmap='GnBu',extend='both')#画图clip=maskout.shp2clip(cs, ax,r'E:\enshi\恩施.shp' ,0) plt.title('恩施州去年累计降水',size=20)##########################################################################################
    position=fig.add_axes([0.97,0.25,0.04,0.5])
    cb=fig.colorbar(cs,cax=position,shrink=0.4,extend='both')
    #绘制colorbar并省称为cbax2=cb.ax#召唤出cb的ax属性并省称为ax2,这时ax2即视为一个子图
    ax2.yaxis.set_ticks_position('left')
    #将数值刻度移动到左侧
    ax2.tick_params(labelsize=10,left=True,right=True)
    #修改刻度样式,并使左右都有刻度
    ax3=ax2.secondary_yaxis('right')
    #新建ax3,使ax3与ax2完全相同ax3.spines['right'].set_bounds(900,1900)
    #截去多余的部分ax3.set_yticks([900,1100,1300,1500,1700,1900])
    ax3.set_yticklabels(['缺水','一般性缺水','收支充足','降水丰沛','有可能涝灾','成灾'])
    #将ax3上的定量数值转化为定性文字 
  12. 多子图共用,色卡

    plt.colorbar(ac, ax=[ax[0], ax[1]], location='bottom', )   # https://www.jianshu.com/p/d97c1d2e274f

     

    # -*- coding: utf-8 -*-
    """
    Created on Sat Sep 5 18:05:11 2020
    @author: 15025
    draw three figures with one common colorbar
    """
    
    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import ImageGrid
    
    
    class Visualazation:
      def mainProgram(self):
        # Set up figure and image grid
        fig = plt.figure(figsize=(8, 4))
        
        grid = ImageGrid(fig, 111,
                 nrows_ncols=(1,3),
                 axes_pad=0.15,
                 share_all=True,
                 cbar_location="right",
                 cbar_mode="single",
                 cbar_size="7%",
                 cbar_pad=0.15,
                 )
        
        # Add data to image grid
        for ax in grid:
          im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
        
        # Colorbar
        ax.cax.colorbar(im)
        ax.cax.toggle_label(True)
        
        plt.show()
        
    
    if __name__ == "__main__":
      main = Visualazation()
      main.mainProgram()
    ImageGrid()函数参数说明:nrows_ncols=(1,3)表示创建一个1行3列的画布。share_all=True表示所画的图像公用x坐标轴和y坐标轴。
    cbar_location="right"表示colorbar位于图像的右侧,当然也可以位于上方,下方和左侧。cbar_mode="single"表示三个图像公用一个colorbar。
    cbar_size="7%"表示colorbar的尺寸,默认值为5%。cbar_pad=0.15表示图像与colorbar之间的填充间距,默认值为5%。可以自行调整以上数值进行尝试。

    参考: https://www.jb51.net/article/195331.htm    

  参考: https://blog.csdn.net/weixin_39790102/article/details/111663606

 

posted on 2022-08-29 16:59  闹不机米  阅读(997)  评论(0编辑  收藏  举报

导航