Import libraries
In [1]:
import numpy as np
from numpy.random import seed
from numpy.random import rand
import math

import matplotlib.pyplot as plt
%matplotlib inline
Create example data
In [2]:
seed(50)
x = np.sort(np.random.randint(low=1, high=100, size=1000000))
y = [math.exp(n) for n in x]
Create simple plot
In [3]:
plt.plot(x, y)
plt.title("Simple Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show();
Create plot within a figure
In [4]:
plt.figure(figsize=(15,5))
plt.plot(x, y)
plt.title("Plot within a Figure")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
Create subplots without a figure
In [5]:
plt.subplot(1,2,1)
plt.plot(x, y)
plt.title("Subplot I")
plt.xlabel("x")
plt.ylabel("y")

plt.subplot(1,2,2)
plt.plot(x, y)
plt.title("Subplot II")
plt.xlabel("x")
plt.ylabel("y")

plt.suptitle("Subplots")
plt.show()
Create subplots within a figure added to axes
In [6]:
fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10,10))
ax[0,1].plot(x,y)
ax[1,0].plot(x,y)
ax[0,1].set_title("Subplot I")
ax[1,0].set_title("Subplot II")
plt.show()
Scatterplots & Histograms
In [7]:
data = [n * 100 for n in np.array([np.random.normal(size=100)])]

plt.hist(data)
plt.title("Histogram")
plt.show()
In [8]:
plt.xlim(0,10)
plt.ylim(0,5000)
plt.scatter(x, y)
plt.title("Scatter")
plt.xlabel("x")
plt.ylabel("y")
plt.show()
3D Plotting
In [9]:
from mpl_toolkits import mplot3d

ax = plt.axes(projection='3d')
ax.scatter3D(x,y)
ax.set_xlabel("x")
ax.set_ylabel("y")
plt.show()

Saving as Images

In [10]:
plt.savefig("example.png")
plt.savefig("example.png", transparent=True)
<Figure size 432x288 with 0 Axes>
Styling
In [11]:
x = np.sort(np.random.randint(low=1, high=100, size=100))
y = [n ** 2 for n in x]

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10,10), edgecolor="green")

ax[0,1].plot(x,y, color='orange', linestyle=':', linewidth=1)
ax[0,1].grid(color='red', linestyle='-', linewidth=1)
ax[0,1].set_title("Plot")

ax[0,0].plot(x,y, color='green', linestyle='--', linewidth=1)
ax[0,0].set_title("Plot")

ax[1,0].scatter(x,y, color='magenta', marker='^')
ax[1,0].grid(color='purple', linestyle='-', linewidth=1)
ax[1,0].set_title("Scatter")

ax[1,1].scatter(x,y, color='cyan', marker='*')
ax[1,1].set_title("Scatter")

plt.show()
In [12]:
plt.style.available[:5]
Out[12]:
['seaborn-poster',
 'bmh',
 'seaborn-deep',
 'seaborn-notebook',
 'fivethirtyeight']
In [13]:
plt.style.use('fivethirtyeight')

plt.hist(data)
plt.title("Histogram")
plt.show()
In [14]:
with plt.style.context('bmh'):
    plt.hist(data)
    plt.title("Histogram")
    plt.show()