In [141]:
data_bi,data_po,target_bi,target_po = makeData(6000)


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-141-b41f8f52787e> in <module>()
----> 1 data_bi,data_po,target_bi,target_po = makeData(6000)

<ipython-input-4-7520e1f61292> in makeData(radCut)
     12     for el in Uncleaned_po:
     13         if el[3]==1.0 and el[4]==0.0 and el[1]<radCut:
---> 14             data_po.append([el[0],el[2]])
     15     #shuffle(data_po)
     16     data_po=np.array(data_po)

KeyboardInterrupt: 

In [1]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import style 
style.use('ggplot')
import numpy as np
import pandas as pd
from sklearn.neural_network import MLPClassifier
from sklearn.cross_validation import train_test_split
from matplotlib.colors import LinearSegmentedColormap
from matplotlib import gridspec


from random import shuffle
import random

import matplotlib.cm as cm


/home/billy/anaconda2/lib/python2.7/site-packages/sklearn/cross_validation.py:43: DeprecationWarning: This module has been deprecated in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
  "This module will be removed in 0.20.", DeprecationWarning)

data_bi=np.loadtxt("Classifier_data_bi_sample.dat",skiprows=1,delimiter=",",usecols=(0,2))

target_bi=np.ones(data_bi.shape[0])

data_po=np.loadtxt("Classifier_data_po_sample.dat",skiprows=1,delimiter=",",usecols=(0,2))

target_po=np.zeros(data_po.shape[0])

data_bi=np.loadtxt("Classifier_data_bi.dat",skiprows=1,delimiter=",",usecols=(0,2)) shuffle(data_bi) target_bi=np.ones(data_bi.shape[0]) data_po=np.loadtxt("Classifier_data_po.dat",skiprows=1,delimiter=",",usecols=(0,2)) shuffle(data_po) target_po=np.zeros(data_po.shape[0])


In [2]:
Uncleaned_bi=np.loadtxt("Classifier_data_bi.dat",skiprows=1,delimiter=",")
np.random.shuffle(Uncleaned_bi)

Uncleaned_po=np.loadtxt("Classifier_data_po.dat",skiprows=1,delimiter=",")
np.random.shuffle(Uncleaned_po)

In [ ]:
data_bi= Uncleaned_bi[reduce(np.logical_and,[Uncleaned_bi[:,3]==1,Uncleaned_bi[:,4]==0,Uncleaned_bi[:,1]<4000])][:,[0,2]]
data_po= Uncleaned_po[reduce(np.logical_and,[Uncleaned_po[:,3]==1,Uncleaned_po[:,4]==0,Uncleaned_po[:,1]<4000])][:,[0,2]]
target_bi=np.ones(data_bi.shape[0])
target_po=np.zeros(data_po.shape[0])
print "len(data_bi)",len(data_bi)

In [ ]:
data_bi[:,[0,2]]

In [26]:
lis=[Uncleaned_bi[:,3]==1,Uncleaned_bi[:,4]==0,Uncleaned_bi[:,1]<4000]
Uncleaned_bi[reduce(np.logical_and,[Uncleaned_bi[:,3]==1,Uncleaned_bi[:,4]==0,Uncleaned_bi[:,1]<5000])]


Out[26]:
array([[  1.26624000e+00,   4.14427000e+03,  -7.70772000e+01,
          1.00000000e+00,   0.00000000e+00],
       [  7.53853000e-01,   3.12568000e+03,  -5.02668000e+01,
          1.00000000e+00,   0.00000000e+00],
       [  2.01693000e+00,   4.78015000e+03,  -1.46781000e+02,
          1.00000000e+00,   0.00000000e+00],
       ..., 
       [  3.58111000e-01,   3.90701000e+03,  -2.12830000e+01,
          1.00000000e+00,   0.00000000e+00],
       [  6.62413000e-01,   4.52702000e+03,  -4.67250000e+01,
          1.00000000e+00,   0.00000000e+00],
       [  2.22728000e+00,   3.84017000e+03,  -1.43248000e+02,
          1.00000000e+00,   0.00000000e+00]])

In [34]:
plt.scatter(data_bi[:,0], data_bi[:,1], c='red', alpha=0.5,marker='+')
plt.scatter(data_po[:,0], data_po[:,1], c='blue', alpha=0.5,marker='+')
plt.xlim([0,2.5])
plt.ylim([-160,100])
plt.show()



In [ ]:
data=np.concatenate((data_bi,data_po))
target=np.concatenate((target_bi,target_po))
X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)
print X_test
print y_test

In [ ]:
neuNet= MLPClassifier(activation= 'logistic', algorithm='adam', alpha=1e-4, hidden_layer_sizes=(3, 2), random_state=42)

In [ ]:
neuNet.fit(X_train,y_train)

In [ ]:
print neuNet.score(X_test,y_test)

In [ ]:
x = np.linspace(0,2.6,1000)
y = np.linspace(-160,100,1000)
xx, yy = np.meshgrid(x, y)
#print np.c_[xx.ravel(), yy.ravel()]
Z = neuNet.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
print Z.shape
print Z

In [3]:
def findPerformance(rad):
    data_bi= Uncleaned_bi[reduce(np.logical_and,[Uncleaned_bi[:,3]==1,Uncleaned_bi[:,4]==0,Uncleaned_bi[:,1]<rad])][:,[0,2]]
    data_po= Uncleaned_po[reduce(np.logical_and,[Uncleaned_po[:,3]==1,Uncleaned_po[:,4]==0,Uncleaned_po[:,1]<rad])][:,[0,2]]
    target_bi=np.ones(data_bi.shape[0])
    target_po=np.zeros(data_po.shape[0])
    data=np.concatenate((data_bi,data_po))
    target=np.concatenate((target_bi,target_po))
    
    X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)
    neuNet= MLPClassifier(activation= 'logistic', algorithm='adam', alpha=1e-4, hidden_layer_sizes=(3, 2), random_state=42)
    neuNet.fit(X_train,y_train)
    
    test_bi=X_test[y_test==0]
    test_po=X_test[y_test==1]
    
    print "rad cut = ",rad
    bool_bi= neuNet.predict(test_bi)==0
    N_bi=float(len(test_bi))
    n_bi=float(np.sum(bool_bi))   
    bool_po = neuNet.predict(test_po)==0
    N_po=float(len(test_po))
    n_po=float(np.sum(bool_po))
    err_bi=(n_bi/N_bi)*np.sqrt((n_bi+N_bi)/(n_bi*N_bi))
    err_po=(n_po/N_po)*np.sqrt((n_po+N_po)/(n_po*N_po))
    print "beta pass = ",neuNet.score(test_bi,np.zeros(len(test_bi)))*100, "+/- ", str(err_bi*100)
    print "alpha pass = ",neuNet.score(test_po,np.zeros(len(test_po)))*100, "+/- ", str(err_po*100)

In [4]:
for i in range(4000,7000,1000):
    findPerformance(i)


rad cut =  4000
beta pass =  99.6008720633 +/-  0.335962797318
alpha pass =  0.562955644887 +/-  0.021957983941
rad cut =  5000
beta pass =  99.6189760965 +/-  0.240590367951
alpha pass =  0.539932802552 +/-  0.0153806027411
rad cut =  6000
beta pass =  99.6331235992 +/-  0.185397155011
alpha pass =  0.76213521954 +/-  0.0140901940073

In [189]:
data_bi= Uncleaned_bi[np.logical_and(Uncleaned_bi[:,3]==1,Uncleaned_bi[:,4]==0,Uncleaned_bi[:,1]<6000)][:,np.array([0,2])]
    data_po= Uncleaned_po[np.logical_and(Uncleaned_po[:,3]==1,Uncleaned_po[:,4]==0,Uncleaned_po[:,1]<6000)][:,np.array([0,2])]
    target_bi=np.ones(data_bi.shape[0])
    target_po=np.zeros(data_po.shape[0])
    data=np.concatenate((data_bi,data_po))
    target=np.concatenate((target_bi,target_po))
    
    X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)
    neuNet= MLPClassifier(activation= 'logistic', algorithm='adam', alpha=1e-4, hidden_layer_sizes=(3, 2), random_state=42)
    neuNet.fit(X_train,y_train)
    test_bi=X_test[y_test==0]
    test_po=X_test[y_test==1]
    
    print "rad cut = ",6000
    bool_bi= neuNet.predict(test_bi)==0
    N_bi=float(len(test_bi))
    n_bi=float(np.sum(bool_bi))   
    bool_po = neuNet.predict(test_po)==0
    N_po=float(len(test_po))
    n_po=float(np.sum(bool_po))
    print "beta pass = ",neuNet.score(test_bi,np.zeros(len(test_bi)))*100
    print "alpha pass = ",neuNet.score(test_po,np.zeros(len(test_po)))*100


rad cut =  6000
beta pass =  99.5679945638
alpha pass =  0.655402207698

In [190]:
data_bi= Uncleaned_bi[np.logical_and(Uncleaned_bi[:,3]==1,Uncleaned_bi[:,4]==0,Uncleaned_bi[:,1]<5000)][:,np.array([0,2])]
    data_po= Uncleaned_po[np.logical_and(Uncleaned_po[:,3]==1,Uncleaned_po[:,4]==0,Uncleaned_po[:,1]<5000)][:,np.array([0,2])]
    target_bi=np.ones(data_bi.shape[0])
    target_po=np.zeros(data_po.shape[0])
    data=np.concatenate((data_bi,data_po))
    target=np.concatenate((target_bi,target_po))
    
    X_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42)
    neuNet= MLPClassifier(activation= 'logistic', algorithm='adam', alpha=1e-4, hidden_layer_sizes=(3, 2), random_state=42)
    neuNet.fit(X_train,y_train)
    test_bi=X_test[y_test==0]
    test_po=X_test[y_test==1]
    
    print "rad cut = ",4000
    bool_bi= neuNet.predict(test_bi)==0
    N_bi=float(len(test_bi))
    n_bi=float(np.sum(bool_bi))   
    bool_po = neuNet.predict(test_po)==0
    N_po=float(len(test_po))
    n_po=float(np.sum(bool_po))
    print "beta pass = ",neuNet.score(test_bi,np.zeros(len(test_bi)))*100
    print "alpha pass = ",neuNet.score(test_po,np.zeros(len(test_po)))*100


rad cut =  4000
beta pass =  99.4412639089
alpha pass =  10.7023445594

In [ ]:


In [83]:
colors = [(0.2, 0.9, 0.9),(0.6,0.2,0.2)]  # R -> G -> B
n_bins = 2  # Discretizes the interpolation into bins
cmap_name = 'my_list'
cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bins)

fig = plt.figure(figsize=(20, 6)) 
gs = gridspec.GridSpec(1, 2, width_ratios=[1, 1.2]) 
ax = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

ax.imshow(Z, vmin=0, vmax=1,
           extent=[x.min(), x.max(), y.min(), y.max()],
           interpolation='nearest',aspect="auto",origin='lower',cmap=cm)

ax.set_title('Cut boundary from a primitive neural network',fontsize=20,y=1.05)
ax.set_xlabel('mcEdepQuenched (MeV)',fontsize=16)
ax.set_ylabel('BerkeleyAlphaBeta',fontsize=16)
ax.set_xlim([0,2.5])
ax.set_ylim([-160,100])

plot1=ax2.imshow(Z, vmin=0, vmax=1,
           extent=[x.min(), x.max(), y.min(), y.max()],
           interpolation='nearest',aspect="auto",origin='lower', cmap=cm)

ax2.set_title('Cut boundary with points',fontsize=20,y=1.05)
ax2.set_xlabel('mcEdepQuenched (MeV)',fontsize=16)
ax2.set_ylabel('BerkeleyAlphaBeta',fontsize=16)
ax2.scatter(data_bi[:,0], data_bi[:,1], alpha=0.2,facecolors='none', edgecolors='r')
ax2.scatter(data_po[:,0], data_po[:,1], alpha=0.2,facecolors='none', edgecolors='b')
ax2.set_xlim([0,2.5])
ax2.set_ylim([-160,100])
ax2.annotate(r'Probably of a $\beta$', xy=(2, 1), xytext=(3, 10),rotation=270,fontsize=16)
ax2.annotate(r'Success at tagging test data = '+str(round(neuNet.score(X_test,y_test),4)), xy=(2, 1), xytext=(0.3, 75),  rotation=0,fontsize=16)

cbar = fig.colorbar(plot1,orientation='vertical')

fig.savefig("Neural_Network_Boundary_r_4000.png")
fig.show()



In [115]:
test_bi=X_test[y_test==0]
test_po=X_test[y_test==1]

In [116]:
boolarr=neuNet.predict(test_bi)==0
N=float(len(test_bi))
n=float(np.sum(boolarr))
print "N = ", N
print "n = ",n
print "fraction passed = ",float(n/N)


N =  578669.0
n =  575847.0
fraction passed =  0.995123291554

In [117]:
print neuNet.score(test_bi,np.zeros(len(test_bi)))*100
print neuNet.score(test_po,np.zeros(len(test_po)))*100


99.5123291554
0.574445202788

In [82]:
plt.scatter(test_bi[:,0],test_bi[:,1],c="r")
plt.scatter(test_po[:,0],test_po[:,1],c="b")
plt.xlim([0,2.5])
plt.ylim([-160,100])


Out[82]:
(-160, 100)

In [45]:
plt.imshow(Z, vmin=0, vmax=1,interpolation='nearest',
           extent=[x.min(), x.max(), y.min(), y.max()],aspect="auto",origin='lower',cmap=cm)
plt.scatter(data_bi[:1000,0], data_bi[:1000,1], alpha=0.2,facecolors='none', edgecolors='r')
plt.scatter(data_po[:1000,0], data_po[:1000,1], alpha=0.2,facecolors='none', edgecolors='b')


Out[45]:
<matplotlib.collections.PathCollection at 0x7f4ad5e19e90>

In [ ]:


In [ ]:


In [ ]:


In [57]:
import matplotlib.pyplot as plt
import numpy as np

plt.subplot(211)
plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)
plt.subplot(212)
plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)

#plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)
cax = plt.axes([0.85, 0.1, 0.075, 0.8])
plt.colorbar(cax=cax)
plt.show()



In [60]:
import matplotlib.pyplot as plt
import numpy as np

plt.subplot(211)
plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)
plt.subplot(212)
plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)

plt.subplots_adjust(bottom=0.1, right=1, top=0.9)
cax = plt.axes([0.85, 0.1, 0.075, 0.8])
plt.colorbar(cax=cax)
plt.show()



In [ ]:


In [ ]:


In [ ]:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
import numpy as np

#cmaplist=[[0.1,0.4,0.1,1],[0.6,0.1,0.1,1]]

# define the colormap
cmap = plt.cm.jet
print cmap.N
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
#cmaplist[0] = (.5,.5,.5,1.0)
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

print (np.amin(x), np.amax(x), np.amin(y), np.amax(y))

#plt.imshow(Z,extent=(np.amin(x), np.amax(x), np.amin(y), np.amax(y)),aspect="auto")
plt.pcolor(x,y,Z,cmap="RdBu",vmin=0., vmax=1.)

plt.colorbar()
plt.scatter(data_bi[:,0], data_bi[:,1], c='red', alpha=0.5,marker='+')
plt.scatter(data_po[:,0], data_po[:,1], c='blue', alpha=0.5,marker='+')
plt.xlim([0,2.5])
plt.ylim([-160,100])
plt.show()

In [ ]:
plt.imshow(Z, cmap='RdBu', vmin=0, vmax=1,
           extent=[x.min(), x.max(), y.min(), y.max()],
           interpolation='nearest', origin='lower',aspect="auto")
plt.title('image (interp. nearest)')
plt.colorbar()
plt.scatter(data_bi[:1000,0], data_bi[:1000,1], c='red', alpha=0.5,marker='+')
plt.scatter(data_po[:1000,0], data_po[:1000,1], c='blue', alpha=0.5,marker='+')
plt.xlim([0,2.5])
plt.ylim([-160,100])

In [ ]:


In [ ]:
# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))

# define the data
x = np.random.rand(20)
y = np.random.rand(20)
tag = np.random.randint(0,20,20)
tag[10:12] = 0 # make sure there are some 0 values to showup as grey

# define the colormap

cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# force the first color entry to be grey
cmaplist[0] = (.5,.5,.5,1.0)
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0,20,21)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x,y,c=tag,s=np.random.randint(100,500,20),cmap=cmap, norm=norm)

# create a second axes for the colorbar
ax2 = fig.add_axes([0.95, 0.1, 0.03, 0.8])
cb = mpl.colorbar.ColorbarBase(ax2, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds, boundaries=bounds, format='%1i')

ax.set_title('Well defined discrete colors')
ax2.set_ylabel('Very custom cbar [-]', size=12)

In [ ]:
#!/usr/bin/env python

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

"""
Creating a colormap from a list of colors
-----------------------------------------
Creating a colormap from a list of colors can be done with the `from_list`
method of `LinearSegmentedColormap`. You must pass a list of RGB tuples that
define the mixture of colors from 0 to 1.


Creating custom colormaps
-------------------------
It is also possible to create a custom mapping for a colormap. This is
accomplished by creating dictionary that specifies how the RGB channels
change from one end of the cmap to the other.

Example: suppose you want red to increase from 0 to 1 over the bottom
half, green to do the same over the middle half, and blue over the top
half.  Then you would use:

cdict = {'red':   ((0.0,  0.0, 0.0),
                   (0.5,  1.0, 1.0),
                   (1.0,  1.0, 1.0)),

         'green': ((0.0,  0.0, 0.0),
                   (0.25, 0.0, 0.0),
                   (0.75, 1.0, 1.0),
                   (1.0,  1.0, 1.0)),

         'blue':  ((0.0,  0.0, 0.0),
                   (0.5,  0.0, 0.0),
                   (1.0,  1.0, 1.0))}

If, as in this example, there are no discontinuities in the r, g, and b
components, then it is quite simple: the second and third element of
each tuple, above, is the same--call it "y".  The first element ("x")
defines interpolation intervals over the full range of 0 to 1, and it
must span that whole range.  In other words, the values of x divide the
0-to-1 range into a set of segments, and y gives the end-point color
values for each segment.

Now consider the green. cdict['green'] is saying that for
0 <= x <= 0.25, y is zero; no green.
0.25 < x <= 0.75, y varies linearly from 0 to 1.
x > 0.75, y remains at 1, full green.

If there are discontinuities, then it is a little more complicated.
Label the 3 elements in each row in the cdict entry for a given color as
(x, y0, y1).  Then for values of x between x[i] and x[i+1] the color
value is interpolated between y1[i] and y0[i+1].

Going back to the cookbook example, look at cdict['red']; because y0 !=
y1, it is saying that for x from 0 to 0.5, red increases from 0 to 1,
but then it jumps down, so that for x from 0.5 to 1, red increases from
0.7 to 1.  Green ramps from 0 to 1 as x goes from 0 to 0.5, then jumps
back to 0, and ramps back to 1 as x goes from 0.5 to 1.

row i:   x  y0  y1
                /
               /
row i+1: x  y0  y1

Above is an attempt to show that for x in the range x[i] to x[i+1], the
interpolation is between y1[i] and y0[i+1].  So, y0[0] and y1[-1] are
never used.

"""
# Make some illustrative fake data:

x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2*np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.sin(Y) * 10


# --- Colormaps from a list ---

colors = [(0, 0, 0),(1,1,1)]  # R -> G -> B
n_bins = [2, 6, 10, 100]  # Discretizes the interpolation into bins
cmap_name = 'my_list'
fig, axs = plt.subplots(2, 2, figsize=(6, 9))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
for n_bin, ax in zip(n_bins, axs.ravel()):
    # Create the colormap
    cm = LinearSegmentedColormap.from_list(
        cmap_name, colors, N=n_bin)
    # Fewer bins will result in "coarser" colomap interpolation
    im = ax.imshow(Z, interpolation='nearest', origin='lower', cmap=cm)
    ax.set_title("N bins: %s" % n_bin)
    fig.colorbar(im, ax=ax)


# --- Custom colormaps ---

cdict1 = {'red':   ((0.0, 0.0, 0.0),
                   (0.5, 0.0, 0.1),
                   (1.0, 1.0, 1.0)),

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 1.0),
                   (0.5, 0.1, 0.0),
                   (1.0, 0.0, 0.0))
        }

cdict2 = {'red':   ((0.0, 0.0, 0.0),
                   (0.5, 0.0, 1.0),
                   (1.0, 0.1, 1.0)),

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.1),
                   (0.5, 1.0, 0.0),
                   (1.0, 0.0, 0.0))
        }

cdict3 = {'red':  ((0.0, 0.0, 0.0),
                   (0.25, 0.0, 0.0),
                   (0.5, 0.8, 1.0),
                   (0.75, 1.0, 1.0),
                   (1.0, 0.4, 1.0)),

         'green': ((0.0, 0.0, 0.0),
                   (0.25, 0.0, 0.0),
                   (0.5, 0.9, 0.9),
                   (0.75, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.4),
                   (0.25, 1.0, 1.0),
                   (0.5, 1.0, 0.8),
                   (0.75, 0.0, 0.0),
                   (1.0, 0.0, 0.0))
        }

# Make a modified version of cdict3 with some transparency
# in the middle of the range.
cdict4 = cdict3.copy()
cdict4['alpha'] = ((0.0, 1.0, 1.0),
                #   (0.25,1.0, 1.0),
                   (0.5, 0.3, 0.3),
                #   (0.75,1.0, 1.0),
                   (1.0, 1.0, 1.0))


# Now we will use this example to illustrate 3 ways of
# handling custom colormaps.
# First, the most direct and explicit:

blue_red1 = LinearSegmentedColormap('BlueRed1', cdict1)

# Second, create the map explicitly and register it.
# Like the first method, this method works with any kind
# of Colormap, not just
# a LinearSegmentedColormap:

blue_red2 = LinearSegmentedColormap('BlueRed2', cdict2)
plt.register_cmap(cmap=blue_red2)

# Third, for LinearSegmentedColormap only,
# leave everything to register_cmap:

plt.register_cmap(name='BlueRed3', data=cdict3)  # optional lut kwarg
plt.register_cmap(name='BlueRedAlpha', data=cdict4)

# Make the figure:

fig, axs = plt.subplots(2, 2, figsize=(6, 9))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)

# Make 4 subplots:

im1 = axs[0, 0].imshow(Z, interpolation='nearest', cmap=blue_red1)
fig.colorbar(im1, ax=axs[0, 0])

cmap = plt.get_cmap('BlueRed2')
im2 = axs[1, 0].imshow(Z, interpolation='nearest', cmap=cmap)
fig.colorbar(im2, ax=axs[1, 0])

# Now we will set the third cmap as the default.  One would
# not normally do this in the middle of a script like this;
# it is done here just to illustrate the method.

plt.rcParams['image.cmap'] = 'BlueRed3'

im3 = axs[0, 1].imshow(Z, interpolation='nearest')
fig.colorbar(im3, ax=axs[0, 1])
axs[0, 1].set_title("Alpha = 1")

# Or as yet another variation, we can replace the rcParams
# specification *before* the imshow with the following *after*
# imshow.
# This sets the new default *and* sets the colormap of the last
# image-like item plotted via pyplot, if any.
#

# Draw a line with low zorder so it will be behind the image.
axs[1, 1].plot([0, 10*np.pi], [0, 20*np.pi], color='c', lw=20, zorder=-1)

im4 = axs[1, 1].imshow(Z, interpolation='nearest')
fig.colorbar(im4, ax=axs[1, 1])

# Here it is: changing the colormap for the current image and its
# colorbar after they have been plotted.
im4.set_cmap('BlueRedAlpha')
axs[1, 1].set_title("Varying alpha")
#

fig.suptitle('Custom Blue-Red colormaps', fontsize=16)

plt.show()

In [ ]:
a = ['Spears', "Adele", "NDubz", "Nicole", "Cristina"]
b = [1,2,3,4,5]
z = zip(a, b)
# => [('Spears', 1), ('Adele', 2), ('NDubz', 3), ('Nicole', 4), ('Cristina', 5)]
random.shuffle(z)
a, b = zip(*z)

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
x = np.arange(0, np.pi, 0.1)
y = np.arange(0, 2*np.pi, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.cos(X) * np.sin(Y) * 10


# --- Colormaps from a list ---

colors = [(1, 1, 1),(0,0,0)]  # R -> G -> B
n_bins = 2  # Discretizes the interpolation into bins
cmap_name = 'my_list'

fig, axs = plt.subplots(1, 1, figsize=(6, 6))
fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)

# Create the colormap
cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bins)
# Fewer bins will result in "coarser" colomap interpolation
im = axs.imshow(Z, interpolation='nearest', origin='lower', cmap=cm)
axs.set_title("N bins: %s" % n_bins)
fig.colorbar(im, ax=axs)

In [ ]:

import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt

fig = plt.figure() ax = fig.add_subplot(111, projection='3d')

ax.scatter(data_bi[:,1], data_bi[:,2], data_bi[:,0],c='red', marker="") ax.scatter(data_po[:,1], data_po[:,2], data_po[:,0],c='blue', marker="")

ax.set_xlabel('posr (mm)') ax.set_ylabel('MCEdepQuenched (MeV)') ax.set_zlabel('Bab')

plt.show()


In [4]:
def makeData(radCut):
    data_bi=[]
    data_po=[]
    for el in Uncleaned_bi:
        if el[3]==1.0 and el[4]==0.0 and el[1]<radCut:
            data_bi.append([el[0],el[2]])

    #shuffle(data_bi)
    data_bi=np.array(data_bi)
    target_bi=np.ones(data_bi.shape[0])

    for el in Uncleaned_po:
        if el[3]==1.0 and el[4]==0.0 and el[1]<radCut:
            data_po.append([el[0],el[2]])
    #shuffle(data_po)
    data_po=np.array(data_po)
    target_po=np.zeros(data_po.shape[0])
    return data_bi,data_po,target_bi,target_po

In [ ]: