python matplotlib colorbar setting tick formator/locator changes tick labels

前端 未结 1 1631
长情又很酷
长情又很酷 2020-12-19 09:25

users, I want to customize the ticks on a colorbar. However, I found the following strange behavior. I try to change the tick formator to the default formator (I thought th

相关标签:
1条回答
  • 2020-12-19 09:30

    I just found the solution. One has to call

    bar.update_ticks()
    

    after the formators/locators are changed, see

    http://matplotlib.sourceforge.net/api/colorbar_api.html

    Then everything works well.

    Update:

    Here is also the code which changes the Formator/Locator. It is based on the internal structure of the colorbar-code, so maybe someone else has a better solution:

    #http://matplotlib.sourceforge.net/examples/pylab_examples/griddata_demo.html
    from numpy.random import uniform, seed
    from matplotlib.mlab import griddata
    import matplotlib.pyplot as plt
    import matplotlib.ticker
    import numpy as np
    # make up data.
    seed(0)
    npts = 200
    x = uniform(-2,2,npts)
    y = uniform(-2,2,npts)
    z = x*np.exp(-x**2-y**2)
    # define grid
    xi = np.linspace(-2.1,2.1,100)
    yi = np.linspace(-2.1,2.1,200)
    # grid the data.
    zi = griddata(x,y,z,xi,yi,interp='linear')
    
    ##### PLOT
    plt.figure()
    CS  = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
    bar = plt.colorbar(orientation='horizontal') # draw colorbar
    
    
    tick_locs   = [-3.9e-1,-2.6e-1,-1.3e-1,0e-1,1.3e-1,2.6e-1,3.9e-1]
    tick_labels = ['-0.390','-0.260','-0.130','0','0.13','0.26','0.390']
    
    
    bar.locator     = matplotlib.ticker.FixedLocator(tick_locs)
    bar.formatter   = matplotlib.ticker.FixedFormatter(tick_labels)
    bar.update_ticks()
    
    # plot data points.
    #plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
    plt.xlim(-2,2)
    plt.ylim(-2,2)
    plt.title('griddata test (%d points)' % npts)
    plt.show()
    
    0 讨论(0)
提交回复
热议问题