Let's Build a Simple Graph

In [2]:
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
In [3]:
x = np.arange(0,10)
y = np.arange(0,10)
In [4]:
plt.plot(x,y)
Out[4]:
[<matplotlib.lines.Line2D at 0x1060ab910>]

There are some great defaults to make these plots pretty!

  • ggplot emulates the most popular and beautiful plotting style in R.
  • fivethirtyeight emulates the fivethirtyeight infographic style
In [5]:
print plt.style.available
[u'dark_background', u'bmh', u'grayscale', u'ggplot', u'fivethirtyeight']
In [6]:
plt.style.use('fivethirtyeight')
plt.plot(x,y)
Out[6]:
[<matplotlib.lines.Line2D at 0x106216a10>]
In [7]:
plt.style.use('ggplot')
plt.plot(x,y)
Out[7]:
[<matplotlib.lines.Line2D at 0x106492610>]

Standard Additions to a Chart

In [8]:
x = np.arange(-10,10)
a = np.arange(0,20)
b = [b**2 for b in range(0,20)]
c = [100 for c in range(0,20)]

plt.title("Some Squiggles")
plt.plot(x,a, label='linear')
plt.plot(x,b, label='exponential')
plt.plot(x,c, label='flat')
plt.legend(loc='upper left', frameon=True)
plt.ylabel('The Y Label')
plt.xlabel('The X Label')
Out[8]:
<matplotlib.text.Text at 0x1064a0590>

Scatterplots are Great!

In [19]:
n = 1000
ax = np.random.randn(n)
ay = np.random.randn(n)

plt.scatter(ax, ay)
Out[19]:
<matplotlib.collections.PathCollection at 0x1074776d0>

Using Color

I like using Tableau's color set because of the visual balance. Here's how you load that into matplotlib!

In [10]:
# These are the "Tableau 20" colors as RGB.  
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
             (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
             (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
             (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
             (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]

# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.  
for i in range(len(tableau20)):
    r, g, b = tableau20[i]
    tableau20[i] = (r / 255., g / 255., b / 255.)
In [26]:
# c for color, alpha for transparency
plt.scatter(ax, ay, c=tableau20[4], alpha=0.75)
Out[26]:
<matplotlib.collections.PathCollection at 0x108629c50>