Plotting#

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

try:
    from google.colab import output
    output.enable_custom_widget_manager()
    print('All good to go')
except:
    print('Okay we are not in Colab just proceed as if nothing happened')

Using plt for quick plots#

  • Matplotlib is the most widely used plotting library in the ecosystem of python. In the above cel we loaded matplotlib and the relevant libraries.

  • The easiest way to use matplotlib is via pyplot, which allows you to plot 1D and 2D data. Here is a simple example:

# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)

# Plot the points using matplotlib
plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7f6e01c6a560>]
../_images/e8a0242ed7dcde6129922112a0664da3bb61f66e10e303df81d8d03314dbd86c.png

Using fig, ax objects for subplots and more#

  • For customizing plots it is more convenient to define fig and ax objects.

  • ax and fig can be manipulated using their methods

  • One can then use ax object to make veriety of subplots then use fig to save the entire figure as one pdf.

fig, ax = plt.subplots(figsize=(6,4))

x = np.arange(0, 3 * np.pi, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

# Plot the points using matplotlib
ax.plot(x, y1, label='sin(x)')
ax.plot(x, y2, label='cos(x)')

# Specify labels
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.legend()

#fig.savefig("myfig.pdf")
<matplotlib.legend.Legend at 0x7f6dffac6830>
../_images/3c7f3e03e3a29284d26ac95c57cb1fc3e661ad682a91bb0117b94d790f35b178.png
t = np.arange(0.0,  2*np.pi, 0.1) # create x values
s = np.sin(t)                     # create y values

fig, ax = plt.subplots(nrows=1,ncols=2,figsize=(6,3))          

ax[0].plot(t, s,'-', color='purple', lw=1.0)  # plot on subplot-1
ax[1].plot(t, s**2,'-o', color='green',  lw=1.0)  # plot  on subplot-2

#fig.savefig('sd.png')             # save the figure
[<matplotlib.lines.Line2D at 0x16b028970>]
../_images/374d04ebee839868ecaa36d722efdacc3f78452ae0cf8f73246fe679c7b5b33b.png
x = range(11)
y = range(11)

fig, ax = plt.subplots(nrows=2, ncols=3,
                       sharex=True, sharey=True)

for row in ax:
    for col in row:
        col.plot(x, y)
        
plt.show()

Histogram#

# Make up some random data
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# Plot 1D histogram of the data
plt.hist(x, bins=40, density=True);

Bar plot#

# input data
means = [1, 2, 3]
stddevs = [0.2, 0.4, 0.5]
bar_labels = ['bar 1', 'bar 2', 'bar 3']


# plot bars
x_pos = list(range(len(bar_labels)))
plt.bar(x_pos, means, yerr=stddevs)

plt.show()

Scatter#

x = 1 + 3 * np.random.randn(10000)

y = 2 + 5 * np.random.randn(10000)

plt.scatter(x,y)

Plotting in 2D#

To make 2D plots we need to generate 2D grid \((x,y)\) of points and pass it to our function \(f(x,y)\)

\[f(x,y) = sin(x) \cdot cos(x) \,\,\,\]
x = np.arange(0.0,  2*np.pi, 0.1)   # create x values
y = np.arange(0.0,  2*np.pi, 0.1)   # create y values

X, Y = np.meshgrid(x,y)             # tunring 1D array into 2D grids of x and y values

Z = np.sin(X) * np.cos(Y)           # feed 2D grids to our 2D function f(x,y)

fig, ax = plt.subplots()            # Create fig and ax objects
ax.pcolor(X, Y, Z,cmap='RdBu')                  # plot 

# try also ax.contour, ax.contourf
<matplotlib.collections.PolyCollection at 0x16b04b850>
../_images/b8903e6508c68b7aab4f3447c6c1e41176676709512e4a031c0872c14a5efac0.png

Matplotlib Widgets#

Suppose we would like to explore how the variation of parameter \(\lambda\) affects the following function of a standing wave:

\[f(x) = sin (\omega \cdot x +p)\]
  • Make a python-function which creates a plot as a function of a parameter(s) of interest.

  • Add an interactive widget on top to vary the parameter.

from ipywidgets import widgets
@widgets.interact(phase=(0, 2*np.pi), freq = (0.1, 5))  
def wave(phase=0, freq=0.5):          
    
    x  = np.linspace(0,10,1000)
    y  = np.sin(freq*x+phase)
        
    plt.plot(x, y)
    plt.show()

Interactive plots#

  • Plotly is large multi-language interactive graphing library that covers Python/Julia/R.

  • Plotly-express is a high level library for quick visualizations whihc is similiar to seaborn vs matploltib in its philosophy

  • Pandas is a powerful library for holding labeled tabular data. Plotly heavily relies on pandas dataframe object

df = pd.DataFrame({ 'X':    1*np.random.randn(500), 
                    'Y':    5*np.random.randn(500), 
                    'Z':    np.cos(np.random.randn(500)),
                    'time':  np.arange(500)
                  })
df
import plotly.express as px

fig = px.scatter_3d(df, x='X', y='Y', z='Z')

### Try these other options 

#px.density_heatmap(df, x='X', y='Y')
#px.line(df, x='X', y='Y')
#px.scatter(df, x='X', y='Y')
#px.area(df, x='X', y='Y')
#px.histogram(df, x="X")

fig.show()
../_images/09a36d366a0d1ab50abeb988be13a7ad11baf3fa61fca4f9de9d29a4f9d31f37.png
  • More complex plots can be created using plotly graph objects.

  • You can use chatGPT to help you get started and to customize your plots

import plotly.graph_objects as go 

# Makeup some data
x = np.outer(np.linspace(-2, 2, 30), np.ones(30)) 
y = x.copy().T 
z = np.cos(x ** 2 + y ** 2) 

# Create surface plot
surface = go.Surface(x=x, y=y, z=z)

# Create fig using surface plot
fig = go.Figure(data=[surface]) 

# Customize fig
fig.update_traces(contours_z=dict( 
    show=True, usecolormap=True, 
    highlightcolor="limegreen", 
    project_z=True)) 
  
fig.show() 

Additional resoruces.#

Matplotlib has a huge scientific user base. This means that you can always find a good working template of any kind of visualization which you want to make. With basic understanding of matplotlib and some solid googling skills you can go very far. Here are some additional resources that you may find helpful