EuroSciPy 2015 - matplotlib tutorial

Simple plot

Using defaults


In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

X = np.linspace(-np.pi, np.pi, 265, endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.plot(X,C)
plt.plot(X,S)

plt.show()


Instantiating defaults


In [2]:
# Imports
import numpy as np
import matplotlib.pyplot as plt

# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 1 (pixels)
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")

# Plot sine using green color with a continuous line of width 1 (pixels)
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")

# Set x limits
plt.xlim(-4.0,4.0)

# Set x ticks
plt.xticks(np.linspace(-4,4,9,endpoint=True))

# Set y limits
plt.ylim(-1.0,1.0)

# Set y ticks
plt.yticks(np.linspace(-1,1,5,endpoint=True))

# Save figure using 72 dots per inch
# savefig("../figures/exercice_2.png",dpi=72)

# Show result on screen
plt.show()


Changing colours and line widths


In [3]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

# Show result on screen
plt.show()


Setting limits


In [4]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

# Set x limits
plt.xlim(X.min()*1.1,X.max()*1.1)

# Set y limits
plt.ylim(C.min()*1.1,C.max()*1.1)

# Show result on screen
plt.show()


Setting ticks


In [5]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

# Set x limits
plt.xlim(X.min()*1.1,X.max()*1.1)

# Set y limits
plt.ylim(C.min()*1.1,C.max()*1.1)

# Set x,y ticks
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi])
plt.yticks([-1,0,1])

# Show result on screen
plt.show()


Setting tick labels


In [6]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

# Set x limits
plt.xlim(X.min()*1.1,X.max()*1.1)

# Set y limits
plt.ylim(C.min()*1.1,C.max()*1.1)

# Set x,y ticks
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],
          [r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])
plt.yticks([-1,0,1])

# Show result on screen
plt.show()


Moving spines


In [7]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")

# Set x limits
plt.xlim(X.min()*1.1,X.max()*1.1)

# Set y limits
plt.ylim(C.min()*1.1,C.max()*1.1)

# Set x,y ticks
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],
          [r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])
plt.yticks([-1,0,1])

# Move spines
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

# Show result on screen
plt.show()


Adding a legend


In [8]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

# Set x limits
plt.xlim(X.min()*1.1,X.max()*1.1)

# Set y limits
plt.ylim(C.min()*1.1,C.max()*1.1)

# Set x,y ticks
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],
          [r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])
plt.yticks([-1,0,1])

# Move spines
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

# Add a legend
plt.legend(loc='upper left', frameon=False)

# Show result on screen
plt.show()


Annotate some points


In [9]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

# Set x limits
plt.xlim(X.min()*1.1,X.max()*1.1)

# Set y limits
plt.ylim(C.min()*1.1,C.max()*1.1)

# Set x,y ticks - additional yaxis 0 removed
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],
          [r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])
plt.yticks([-1,1])

# Move spines
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

# Add a legend
plt.legend(loc='upper left', frameon=False)


# Annotate some points

t = 2*np.pi/3
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')

plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
             xy=(t, np.sin(t)), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')

plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
             xy=(t, np.cos(t)), xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

# Show result on screen
plt.show()


Final details


In [10]:
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)

X = np.linspace(-np.pi, np.pi, 256,endpoint=True)
C,S = np.cos(X), np.sin(X)

# Plot cosine using blue color with a continuous line of width 2.5 (pixels)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")

# Plot sine using red color with a continuous line of width 2.5 (pixels)
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

# Set x limits
plt.xlim(X.min()*1.1,X.max()*1.1)

# Set y limits
plt.ylim(C.min()*1.1,C.max()*1.1)

# Set x,y ticks - additional yaxis 0 removed
plt.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],
          [r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])
plt.yticks([-1,1],
          [r'$-1$',r'$+1$'])

# Move spines
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

# Add a legend
plt.legend(loc='upper left', frameon=False)


# Annotate some points

t = 2*np.pi/3
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')

plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
             xy=(t, np.sin(t)), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')

plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
             xy=(t, np.cos(t)), xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(16)
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))

# Show result on screen
plt.show()


Figures, Subplots, Axes and Ticks

Figures

(See webpage for details)

Subplots


In [11]:
from pylab import *

figure(figsize=(8,6), dpi=64)

subplot(2,1,1)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,1,1)',ha='center',va='center',size=24,alpha=.5)

subplot(2,1,2)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,1,2)',ha='center',va='center',size=24,alpha=.5)

show()



In [12]:
from pylab import *

figure(figsize=(8,6), dpi=64)

subplot(1,2,1)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(1,2,1)',ha='center',va='center',size=24,alpha=.5)

subplot(1,2,2)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(1,2,2)',ha='center',va='center',size=24,alpha=.5)

show()



In [13]:
from pylab import *

figure(figsize=(8,6), dpi=64)

subplot(2,2,1)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,1)',ha='center',va='center',size=20,alpha=.5)

subplot(2,2,2)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,2)',ha='center',va='center',size=20,alpha=.5)


subplot(2,2,3)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,3)',ha='center',va='center',size=20,alpha=.5)

subplot(2,2,4)
xticks([]), yticks([])
text(0.5,0.5, 'subplot(2,2,4)',ha='center',va='center',size=20,alpha=.5)

show()



In [14]:
from pylab import *
import matplotlib.gridspec as gridspec

figure(figsize=(8,6), dpi=64)

G = gridspec.GridSpec(3, 3)

axes_1 = subplot(G[0, :])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 1',ha='center',va='center',size=24,alpha=.5)

axes_2 = subplot(G[1,:-1])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 2',ha='center',va='center',size=24,alpha=.5)

axes_3 = subplot(G[1:, -1])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 3',ha='center',va='center',size=24,alpha=.5)

axes_4 = subplot(G[-1,0])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 4',ha='center',va='center',size=24,alpha=.5)

axes_5 = subplot(G[-1,-2])
xticks([]), yticks([])
text(0.5,0.5, 'Axes 5',ha='center',va='center',size=24,alpha=.5)

show()


Axes


In [15]:
from pylab import *

figure(figsize=(8,6), dpi=64)

axes([0.1,0.1,.8,.8])
xticks([]), yticks([])
text(0.6,0.6, 'axes([0.1,0.1,.8,.8])',ha='center',va='center',size=20,alpha=.5)

axes([0.2,0.2,.3,.3])
xticks([]), yticks([])
text(0.5,0.5, 'axes([0.2,0.2,.3,.3])',ha='center',va='center',size=16,alpha=.5)

show()



In [16]:
from pylab import *

figure(figsize=(8,6), dpi=64)

axes([0.1,0.1,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.1,0.1,.8,.8])',ha='left',va='center',size=16,alpha=.5)

axes([0.2,0.2,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.2,0.2,.5,.5])',ha='left',va='center',size=16,alpha=.5)

axes([0.3,0.3,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.3,0.3,.5,.5])',ha='left',va='center',size=16,alpha=.5)

axes([0.4,0.4,.5,.5])
xticks([]), yticks([])
text(0.1,0.1, 'axes([0.4,0.4,.5,.5])',ha='left',va='center',size=16,alpha=.5)

show()


Ticks

(See webpage for details)

Animation

Drip drop


In [19]:
# Imports
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
#%matplotlib nbagg

# New figure with white background
fig = plt.figure(figsize=(6,6), facecolor='white')

# New axis over the whole figure, no frame and a 1:1 aspect ratio
ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)

# Number of ring
n = 50
size_min = 50
size_max = 50*50

# Ring position
P = np.random.uniform(0,1,(n,2))

# Ring colours
C = np.ones((n,4)) * (0,0,0,1)
# Alpha colour channel goes from 0 (transparent) to 1 (opaque)
C[:,3] = np.linspace(0,1,n)

# Ring sizes
S = np.linspace(size_min, size_max, n)

# Scatter plot
scat = ax.scatter(P[:,0], P[:,1], s=S, lw=0.5, edgecolors=C, facecolors='None')

# Ensure limits are [0,1] and remove ticks
ax.set_xlim(0,1), ax.set_xticks([])
ax.set_ylim(0,1), ax.set_yticks([])


def update(frame):
    global P, C, S

    # Every ring is made more transparent
    C[:,3] = np.maximum(0, C[:,3] - 1.0/n)

    # Each ring is made larger
    S += (size_max - size_min) / n

    # Reset ring specific ring (relative to frame number)
    i = frame % 50
    P[i] = np.random.uniform(0,1,2)
    S[i] = size_min
    C[i,3] = 1

    # Update scatter object
    scat.set_edgecolors(C)
    scat.set_sizes(S)
    scat.set_offsets(P)

    # Return the modified object
    return scat,

animation = FuncAnimation(fig, update, interval=10, blit=True, frames=200)
#animation.save('rain.gif', writer='imagemagick', fps=30, dpi=40)
#plt.show()


Earthquakes


In [23]:
'''import urllib
from mpl_toolkits.basemap import Basemap

# -> http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php
feed = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/"

# Significant earthquakes in the last 30 days
# url = urllib.urlopen(feed + "significant_month.csv")

# Magnitude > 4.5
url = urllib.urlopen(feed + "4.5_month.csv")

# Magnitude > 2.5
# url = urllib.urlopen(feed + "2.5_month.csv")

# Magnitude > 1.0
# url = urllib.urlopen(feed + "1.0_month.csv")

# Reading and storage of data
data = url.read().split('\n')[+1:-1]
E = np.zeros(len(data), dtype=[('position',  float, 2),
                               ('magnitude', float, 1)])

for i in range(len(data)):
    row = data[i].split(',')
    E['position'][i] = float(row[2]),float(row[1])
    E['magnitude'][i] = float(row[4])'''


Out[23]:
'import urllib\nfrom mpl_toolkits.basemap import Basemap\n\n# -> http://earthquake.usgs.gov/earthquakes/feed/v1.0/csv.php\nfeed = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/"\n\n# Significant earthquakes in the last 30 days\n# url = urllib.urlopen(feed + "significant_month.csv")\n\n# Magnitude > 4.5\nurl = urllib.urlopen(feed + "4.5_month.csv")\n\n# Magnitude > 2.5\n# url = urllib.urlopen(feed + "2.5_month.csv")\n\n# Magnitude > 1.0\n# url = urllib.urlopen(feed + "1.0_month.csv")\n\n# Reading and storage of data\ndata = url.read().split(\'\n\')[+1:-1]\nE = np.zeros(len(data), dtype=[(\'position\',  float, 2),\n                               (\'magnitude\', float, 1)])\n\nfor i in range(len(data)):\n    row = data[i].split(\',\')\n    E[\'position\'][i] = float(row[2]),float(row[1])\n    E[\'magnitude\'][i] = float(row[4])'

Other types of plot


In [29]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

plt.figure(figsize=(8,6), dpi=80)

n = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)

plt.scatter(X,Y)
plt.show()



In [ ]: