Matplotlib
Special options
[+]Ticks options
[+]Select ticks to appear, e.g, in x-axis
[+]plt.xticks([1E2,1E4,1E6,1E8,1E10,1E12,1E14,1E16])
Ticks font size
[+]matplotlib.rcParams.update({'font.size': 15})
Fix PDF margins
[+]plt.tight_layout()
Label font size, position, etc.
[+]leg=plt.legend(prop={'size':13},loc=(0.33,0.6),...) leg.set_title(r'${\cal L}\ [{\rm fb}^{-1}]$',prop={'size':20})
Special plots
[+]Contours in matplotlib
[+]
Tutorial.
Example: You should have a well defined grid in your data: brfullscan.out (4.9M)
Contour plot with a log scale:
contour( log10(x), log10(y), z )
xlabel('$\mathsf{log}_{10}(x)$')
ylabel('$\mathsf{log}_{10}(y)$')
More info
Make contour from scatter plot
Example: You should have a well defined grid in your data: brfullscan.out (4.9M)
import numpy as np import matplotlib.pyplot as plt from matplotlib import colors, ticker from matplotlib.colors import LogNorm #brfullscan.out format: #If a[:,i] is the i-th column of brfullscan.out, then #a[:,0]=m12, a[:,1]=m0, a[:,16]=decay length a=np.loadtxt('brfullscan.out') x=a[:,0] # np.arange(250,710,10) y=a[:,1] #np.arange(140,2010,10) X,Y=np.meshgrid(x,y) n=x.size m=y.size Z=np.zeros((m,n)) for i in range(m): for j in range(n): Z[i,j]=a[:,16][np.logical_and(a[:,0]==X[i,j],a[:,1]==Y[i,j])] print X[2,0] print Y[2,0] print Z[2,0] print 'm1/2=250 m0=160=>',a[:,16][np.logical_and(a[:,0]==250,a[:,1]==160)],'=' plt.rcParams['xtick.direction'] = 'out' plt.rcParams['ytick.direction'] = 'out' levs=np.array([0.1,1]) plt.pcolor(X,Y,Z,norm=LogNorm(vmin=Z.min(), vmax=Z.max())) plt.colorbar() CS=plt.contour(X,Y,Z,levs,colors='k') plt.clabel(CS, fontsize=12, inline=1,fmt='%1.1f') plt.title('Decay length without boost (mm)',fontsize=18) plt.xlim(250,700) plt.ylim(140,2000) plt.xlabel('$m_{1/2}$ (GeV)',fontsize=18) plt.ylabel('$m_0$ (GeV)',fontsize=18) plt.title('Decay length without boost (mm)',fontsize=18) plt.savefig('dlcontours.png',dpi=600,format='png') plt.show()
Contour plot with a log scale:
contour( log10(x), log10(y), z )
xlabel('$\mathsf{log}_{10}(x)$')
ylabel('$\mathsf{log}_{10}(y)$')
More info
Make contour from scatter plot
Fill area in matplotlib
[+]
To fill the area between two curves as in
#!/usr/bin/env python ''' Fill the region example. ''' import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches #Fig 2 of arXiv:1006.5075 [hep-ph] #x is an array of shape (36,4) # x[:,0]: $\tan^2\theta_{23}$, x[:,1]: Br(W^\pm \tau^\mp)/Br$(W^\pm \mu^\mp)' # x[:,2]: m_{1/2}, x[:,3]=m_0 x=np.asarray([[1.35554795e-02,4.34315945e-02,3.00000000e+02,2.00000000e+02], [2.30389848e-02,5.61037250e-02,3.00000000e+02,2.00000000e+02], [3.46156794e-02,7.41158251e-02,3.00000000e+02,2.00000000e+02], [5.92242227e-02,1.01773328e-01,3.00000000e+02,2.00000000e+02], [8.02790306e-02,1.27973275e-01,3.00000000e+02,2.00000000e+02], [1.68917980e-01,2.28474017e-01,3.00000000e+02,2.00000000e+02], [3.60440590e-01,4.26966565e-01,3.00000000e+02,2.00000000e+02], [4.87684071e-01,5.55345815e-01,3.00000000e+02,2.00000000e+02], [8.64580371e-01,9.18049901e-01,3.00000000e+02,2.00000000e+02], [1.73562531e+00,1.61146867e+00,3.00000000e+02,2.00000000e+02], [2.23188963e+00,2.00509564e+00,3.00000000e+02,2.00000000e+02], [4.57956763e+00,3.49922447e+00,3.00000000e+02,2.00000000e+02], [5.50289894e+00,4.16231461e+00,3.00000000e+02,2.00000000e+02], [8.88421596e+00,5.91643057e+00,3.00000000e+02,2.00000000e+02], [1.83512776e+01,9.55264910e+00,3.00000000e+02,2.00000000e+02], [3.68922849e+01,1.51336192e+01,3.00000000e+02,2.00000000e+02], [5.85489993e+01,1.95532668e+01,3.00000000e+02,2.00000000e+02], [9.18873798e+01,2.34132055e+01,3.00000000e+02,2.00000000e+02], [1.19159113e-02,8.41589835e-02,1.00000000e+03,2.00000000e+03], [1.84322019e-02,9.29407871e-02,1.00000000e+03,2.00000000e+03], [2.79122348e-02,1.16545871e-01,1.00000000e+03,2.00000000e+03], [5.82949043e-02,1.67231748e-01,1.00000000e+03,2.00000000e+03], [8.71995328e-02,2.08982494e-01,1.00000000e+03,2.00000000e+03], [1.14400848e-01,2.40553271e-01,1.00000000e+03,2.00000000e+03], [2.20145773e-01,3.85487245e-01,1.00000000e+03,2.00000000e+03], [4.47537030e-01,6.69951798e-01,1.00000000e+03,2.00000000e+03], [5.52728476e-01,8.00604158e-01,1.00000000e+03,2.00000000e+03], [1.05724478e+00,1.40437005e+00,1.00000000e+03,2.00000000e+03], [2.02759532e+00,2.51541459e+00,1.00000000e+03,2.00000000e+03], [2.50930366e+00,3.05418800e+00,1.00000000e+03,2.00000000e+03], [7.18245450e+00,7.38299455e+00,1.00000000e+03,2.00000000e+03], [1.31714946e+01,1.19295432e+01,1.00000000e+03,2.00000000e+03], [1.62651830e+01,1.50424483e+01,1.00000000e+03,2.00000000e+03], [2.76697962e+01,2.21417330e+01,1.00000000e+03,2.00000000e+03], [4.13090732e+01,3.11325257e+01,1.00000000e+03,2.00000000e+03], [6.38351001e+01,4.28356618e+01,1.00000000e+03,2.00000000e+03]]) fig = plt.figure() ax = fig.add_subplot(111) #ax.vlines(1.06,4E-2,30,lw=10,color='y',label=aNone) mask1=np.logical_and(x[:,2]==1000,x[:,3]==2000) verts1=x[:,0:2][mask1] mask2=np.logical_and(x[:,2]==300,x[:,3]==200) verts2=x[:,0:2][mask2] verts2=verts2[::-1] verts=np.vstack((verts1,verts2)) poly = patches.Polygon(verts,edgecolor='none') ax.add_patch(poly) #ax.loglog() ax.loglog(x[:,0][mask1],x[:,1][mask1],'k--',lw=2,label="$m_{1/2}=1000$ GeV\n $m_0=2000$ GeV") ax.loglog(x[:,0][mask2],x[:,1][mask2],'k-.',lw=3,label="$m_{1/2}=250$ GeV\n $m_0=200$ GeV") ax.legend(loc='upper left') plt.ylim(4E-2,5E1) plt.xlim(1.5E-2,6E1) plt.xlabel(r'$\tan^2\theta_{23}$',fontsize=20) plt.ylabel(r'Br$(W^\pm \tau^\mp)/$Br$(W^\pm \mu^\mp)$',fontsize=20) plt.grid() plt.show()
Hexbin plots
[+]
See
- This
- and this
- Recover 1.x configuration including cmap colormap
mpl.style.use('classic')
- For logarithmic colorbar() use the hexbin option:
from matplotlib.colors import LogNorm norm=LogNorm()
From hexbin to contour(f)
[+]
Illustration of the ise of to convert the random variables `x,y,z` into the uniform grid `xi,yi,zi` to fill scatter plots regions with contours(fills)
See github repo
mlab.griddata(x,y,z,xi,yi,interp='linear')
See github repo
Find frontiers of scatter plots
[+]import numpy as np def pareto_frontier(Xs, Ys, maxX = True, maxY = True): ''' ===================================================================== From: http://oco-carbon.com/metrics/find-pareto-frontiers-in-python/ ===================================================================== Method to take two equally-sized lists and return just the elements which lie on the Pareto frontier, sorted into order. Default behaviour is to find the maximum for both X and Y, but the option is available to specify maxX = False or maxY = False to find the minimum for either or both of the parameters. ''' # Sort the list in either ascending or descending order of X myList = sorted([[Xs[i], Ys[i]] for i in range(len(Xs))], reverse=maxX) # Start the Pareto frontier with the first value in the sorted list p_front = [myList[0]] # Loop through the sorted list for pair in myList[1:]: if maxY: if pair[1] >= p_front[-1][1]: # Look for higher values of Y p_front.append(pair) # and add them to the Pareto frontier else: if pair[1] <= p_front[-1][1]: # Look for lower values of Y p_front.append(pair) # and add them to the Pareto frontier # Turn resulting pairs back into a list of Xs and Ys p_frontX = [pair[0] for pair in p_front] p_frontY = [pair[1] for pair in p_front] return p_frontX, p_frontY if __name__=='__main__': x=[] y=[] for xx in np.random.uniform(0,2,100000): yy=np.random.random() if yy<np.exp(-xx**2): y.append(yy) x.append(xx) X,Y=pareto_frontier(x,y) plt.plot(x,y,'r.') plt.plot(X,Y,'k--',lw=2) plt.ylim(0,1.1) plt.savefig('pareto.png')
Steps
[+]import matplotlib.pyplot as plt plt.plot(range(5), range(5), linestyle='--', drawstyle='steps') plt.plot(range(5), range(5)[::-1], linestyle=':', drawstyle='steps') plt.xlim([-1, 5]) plt.ylim([-1, 5])
Tips Matplotlib
[+]
Assuming:
import matplotlib.pylot as plt
Marker without fill:
[+]
Fill marker with transperence:
[+]
import matplotlib.pylot as plt
Change log to linear
[+]
plt.xscale('linear')
plt.xscale('linear')
plt.xscale('linear')
LaTeX/amsLaTeX in Matplotlib
[+]
To use the true LaTeX:
import matplotlib.pyplot as plt plt.rcParams['text.usetex']=True plt.rcParams['text.latex.preamble']=[r"\usepackage{siunitx}",\ r"\usepackage{amsmath}",\ r"\usepackage{amssymb}",\ r"\usepackage{cancel}"] plt.rcParams['font.family']='serif' plt.rcParams['font.serif']=['serif','Times New Roman','Times'] #plt.rcParams['ps.usedistiller']='xpdf' #proper eps generation
Matplotlib: Obtain the contour from some scatter plot:
[+]import numpy as np def generate_contour_from_scatter(i,outfilefast): ''' Generate a contour with the frontier of a scatter plot, where each x value has minimum and maximum y-values in the down and upper part of the plot. Input: outfilefast: npy file with Numpy array of size (n,m) with m variables and n data. Internally stored in array x. i: # x-axis=x[:,i] of the scatter plot. Change: In this case the scatter plot function is x[:,6]/x[:,7]: change accordingly Output: Numpy array with the contour of the scatter plot ''' x=np.load('%s' %outfilefast) x=x z=np.unique(x[x[:,i]<0][:,i]) #============================================== xx2=[] a=z.tolist() a.reverse() for tanb in a: y=x[x[:,i]==tanb] if y.shape[0]>0: # yy=x[np.logical_and(x[:,i]==tanb,(x[:,6]/x[:,7])==(y[:,6]/y[:,7]).max())] xx2.append(np.asarray(yy.tolist()[0])) xx2=np.asarray(xx2) xx1=[] a=z for tanb in a: y=x[x[:,i]==tanb] if y.shape[0]>0: yy=x[np.logical_and(x[:,i]==tanb,(x[:,6]/x[:,7])==(y[:,6]/y[:,7]).min())] xx1.append(np.asarray(yy.tolist()[0])) xx1=np.asarray(xx1) return np.vstack((xx1,xx2)) if __name__ == '__main__': from pylab import * i=1 outfilefast='scanfast800tbd_eq_tbl.npy' xx=generate_contour_from_scatter(i,outfilefast) plt.semilogy(xx[:,1],xx[:,6]/xx[:,7]) plt.show()
Print a processed LaTeX formula
[+]a = r'\frac{a}{b}' ax = plt.axes([0,0,0.1,0.2]) #left,bottom,width,height ax.set_xticks([]) ax.set_yticks([]) plt.text(0.3,0.4,'$%s$' %a,size=40)
Marker without fill: plt.plot(...,'o',markerfacecolor='none')
[+]plt.plot(...,'o',markerfacecolor='none')
Fill marker with transperence: plt.plot(...,'ro',alpha=0.5)
[+]plt.plot(...,'ro',alpha=0.5)