matplotlib

  • How to use matplotlib to plot beautful figures.
  • Thanks Han Lin for leading us to learn
  • It is very similar to Matlab. One may learn fast if you used to plot by matlab
In [2]:
%matplotlib inline
In [3]:
import matplotlib.pyplot as plt 
In [7]:
plt.plot([1,2,3,4],[1,4,9,16],"ro")
plt.axis([0,6,0,20])
Out[7]:
[0, 6, 0, 20]
In [8]:
import numpy as np
t = np.arange(0,5,0.2)
plt.plot(t,t,'r--',t,t**2,'bs',t,t**3,'g')
plt.plot(t,t**2,'bs')
plt.plot(t,t**3,'g^')
Out[8]:
[<matplotlib.lines.Line2D at 0x18b6970aeb8>]
In [9]:
import math
math.pow(2,3)
Out[9]:
8.0
In [11]:
data = {'a':np.arange(50),
        'c':np.random.randint(0,50,50),
        'd':np.random.randn(50)
       }
data['b'] = data['a'] + 10*np.random.randn(50)
data['d'] = 100*np.abs(data['d'])

plt.figure(figsize=(8,4))
plt.scatter('a','b',c='c',s='d',data=data)
plt.xlabel('entry a')
plt.ylabel('entry.b')
                      
                      
Out[11]:
Text(0, 0.5, 'entry.b')
In [12]:
names = ['group_a','group_b','group_c']
values = [1,10,100]

plt.figure(figsize=(12,4))

plt.subplot(131)
plt.bar(names,values)
plt.subplot(132)
plt.scatter(names,values)
plt.subplot(133)
plt.plot(names,values)
plt.suptitle("test")
Out[12]:
Text(0.5, 0.98, 'test')
In [13]:
def f(t):
    return np.exp(-t)*np.cos(2*np.pi*t)

t1 = np.arange(0,5,0.1)
t2 = np.arange(0,5,0.2)

plt.subplot(211)
plt.plot(t1,f(t1),'bo')
plt.plot(t2,f(t2),'k')
plt.subplot(212)
plt.plot(t2,np.cos(2*np.pi*t2),'r--')
Out[13]:
[<matplotlib.lines.Line2D at 0x18b69869828>]
In [10]:
mu,sigma = 100,15
x = mu + sigma*np.random.randn(10000)

plt.figure(figsize=(16,8))
n,bins,patches = plt.hist(x,50,density=1,facecolor='b',alpha=0.75)

plt.xlabel("Smarts",fontsize=14,color='g')
plt.ylabel("Probability",fontsize=20,color='red')
plt.title("Histgram of IQ")

plt.text(60,0.025,r'$\mu=100,\sigma=15$')
plt.axis([40,160,0,0.03])
plt.grid(True)
In [14]:
ax = plt.subplot(111)

t = np.arange(0., 5., 0.01)
s = np.cos(2*np.pi*t)
# line, =plt.plot(t, s, lw=2)
plt.plot(t, s, lw=2)

# xy是箭头坐标,xytext是标注文字左下角坐标
plt.annotate('local max', xy=(4, 1), xytext=(1, 1.5), arrowprops=dict(facecolor='black', shrink=0.05),)

# 下面两行都能达到同样的目的
# plt.ylim(-2, 2)
plt.axis([-0.3, 5.3, -2, 2])
Out[14]:
[-0.3, 5.3, -2, 2]
In [15]:
from matplotlib.ticker import NullFormatter

np.random.seed(1000)

y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x=  np.arange(len(y))

plt.figure(figsize=(15, 10))

# linear
plt.subplot(221)
plt.plot(x, y)
plt.yscale("linear")
plt.title("linear")
plt.grid(True)

# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale("log")
plt.title("log")
plt.grid(True)

# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
# Adjust the subplot layout, because the logit one may take more space
# than usual, due to y-tick labels like "1 - 10^{-3}"
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
                    wspace=0.35)