June 7, 2014

Numpy / Scipy / Matplotlib - How did I do ... again?




I almost completely switched my computing/plotting tasks from octave to numpy / scipy  and matplotlib.

Here's a little list about things i constantly keep forgetting


Matplotlib

  • manually set the ticks on colorbars:

    from matplotlib import pyplot as plt
    from matplotlib.ticker import FixedLocator
    ...
    cbar = plt.colorbar()
    locs = [0,-10,-20,-30]
    cbar.locator = FixedLocator(locs)
    cbar.update_ticks()

  • define position and size of the colorbar (place it freely somewhere)


    fig = plt.figure(1)
    ...
    is1 = plt.imshow( .... )
    cbaxes = fig.add_axes([0.9, 0.05, 0.02, 0.3])
    cb = fig.colorbar(is1, cax = cbaxes)) 
    cb.ax.tick_params(labelsize=7)


    sources: http://python4mpia.github.io/plotting/advanced.html

  • set position of ticks and labels from left to right axis:

    ax1 = plt.subplot(111)
    ax1.yaxis.tick_right()
    ax1.yaxis.set_label_position("right")


  • reduce the size of the legend

    plt.rcParams['legend.fontsize']=8
    plt.rcParams['legend.borderpad']=0.3
    plt.rcParams['legend.handlelength']=0.1

  • get a second y-axis: ax1a = ax1.twinx() 
  • create a plot on a machine that has no X (running):
    •  
      import matplotlib
      
      # Force matplotlib to not use any Xwindows backend.
      
      matplotlib.use('Agg')

  • Legend location codes:
  • 3d plot minimal example with mplot3d
  • #from plottingtools import *
    from matplotlib import pyplot as plt
    %matplotlib inline
    plt.rcParams['figure.figsize']=(5,4)

    x = np.linspace(-1.5,1.5,501)
    [xx,yy]=np.meshgrid(x,x)
    # some function
    f = np.exp(- (xx**2+yy**2)/0.5**2) \
    + 0.4*np.exp(- ((xx-1)**2+(yy+0.2)**2)/0.5**2) \
    + 0.8*np.exp(- ((xx+1.2)**2+(yy-0.5)**2)/0.5**2)


    from mpl_toolkits.mplot3d import Axes3D
    fig = plt.figure()
    ax = Axes3D(fig)#fig.gca(projection='3d')
    surf = ax.plot_surface(xx,yy,f,
        #cmap=sunrise(),
        antialiased=True,
        linewidth=1,
        rstride=10,
        cstride=10,
        shade=False)
    ax.view_init(75,-80)

    fig2 = plt.figure()
    ax2 = Axes3D(fig2)
    ax2.plot_wireframe(xx,yy,f,
       rstride=10,
       cstride=10)
    ax2.view_init(75,-80)

Numpy

No comments:

Post a Comment