Pascal Triangle

In this IPython Notebook we insert a truncated Pascal triangle, with base containing $n$ elements (n an odd integer), in a masked numpy array and plot it as a Plotly Heatmap.


In [1]:
import numpy as np

In [4]:
def Pascal_array(n):# insert the Pascal triangle in a numpy array (m,n)
    if not n%2:
        raise ValueError('n must be an odd integer')
    m=(n-1)/2+1    
    T=np.zeros((m,n), int)
    c=m-1
    T[0][c]=1
    T[1][c-1]=T[1][c+1]=1

    for i in range(2, m-1):
        for j in range(c-i, c+i+1):
            T[i][j]=T[i-1][j-1]+T[i-1][j+1]
    i=m-1        
    T[i][0]=T[i][n-1]=1

    for j in range(2, n-2):
        T[i][j]=T[i-1][j-1]+T[i-1][j+1] 
    return T

In [5]:
T=Pascal_array(21)
n=T.shape[1]

In [6]:
Ttext=[]
m=T.shape[0]
for k in range(m):
    Ttext.append(['' if item==0 else str(item) for item in T[k]])# convert values to strings in order to annotate the heatmap cells

In [7]:
T= np.ma.masked_equal(T, 0)

In [8]:
X=range(n)
Y=range(m)

The colorscale to plot the Pascal triangle as a heatmap is defined as:


In [10]:
colorsc=[[0.0, 'rgb(77.400000000000006, 58.0, 57.800000000000004)'], 
         [0.33333333, 'rgb(164.19999999999996, 105.99999999999999, 105.40000000000001)'],
         [0.66666, 'rgb(207.59999999999999, 130.0, 129.20000000000002)'], 
         [1.0, 'rgb(251.0, 154.0, 153.0)']]

In [19]:
import plotly.plotly as py
from plotly.graph_objs import *

axisx=dict(showgrid=False,
          zeroline=False,
          showline=False,
          ticks='',
          showticklabels=False)
dy=dict(autorange='reversed')


data = Data([
    Heatmap(
        z=T,
        colorscale=colorsc,
        reversescale=True,
        connectgaps=False,
    )
])
layout = Layout(
    title="Pascal Triangle",
    showlegend=False,
    autosize=True,
    width=800,
    height=450,
    xaxis=XAxis(axisx),
    yaxis=YAxis(dict(axisx, **dy)),# concatenate the two dicts
    
   
    margin=Margin(
        l=40,
        r=20,
        b=30,
        t=60,
       
    ),
)

fig = Figure(data=data, layout=layout)    
annotations = Annotations([
    Annotation(
            showarrow=False, 
            text="Pascal triangle: <a href='https://en.wikipedia.org/wiki/Pascal%27s_triangle'> [1]</a>",  
            xref='paper',     
            yref='paper',     
            x=0,  
            y=-0.09,  
            xanchor='left',   
            yanchor='bottom',  
            font=Font(
            size=0 )
            )
])

#Insert  text from Ttext in the corresponding cells
for i, row in enumerate(Ttext):
    for j, s in enumerate(row):
        annotations.append(
            Annotation(
                text=s, 
                x=X[j], y=Y[i],
                xref='x1', yref='y1',
                font=dict(color='white' if T[i][j]>35 else 'rgb(25,25,25)'),
                showarrow=False)
        )
        
fig['layout'].update(
annotations=annotations
)  
py.sign_in('empet', 'my_api_key')
py.iplot(fig, filename='Pascal-triangle', width=1000)


Out[19]:

In [20]:
from IPython.core.display import HTML
def  css_styling():
    styles = open("./custom.css", "r").read()
    return HTML(styles)
css_styling()


Out[20]: