1. 程式人生 > >使用python中的Matplotlib繪圖示例(續)

使用python中的Matplotlib繪圖示例(續)

下面給出一些比較高階的例子:

注意:

程式碼中需要儲存執行結果圖, 需要事先在當前原始碼目錄下建立一個figure資料夾來存放圖片.

一.數學圖形

#!/usr/bin/env python
#encoding: utf-8

#numpy is accessible via 'np' alias
from pylab import *

figure(figsize=(8,5), dpi=80)

subplot(111)

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

plot(X, C, color="blue", linewidth=2.5, linestyle='-', label='cosine')
plot(X, S, color="red", linewidth=2.5, linestyle='-', label='sine')

ax = 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))

xlim(X.min()*1.1, X.max()*1.1)
xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
ylim(C.min()*1.1, C.max()*1.1)
yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$'])

t = 2*np.pi/3
plot([t,t], [0,np.cos(t)], color='blue', linewidth=1.5, linestyle='--')
scatter([t,], [np.cos(t),], 50, color='blue')
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'))

plot([t,t], [0,np.sin(t)], color='red', linewidth=1.5, linestyle='--')
scatter([t,], [np.sin(t),], 50, color='red')
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'))

legend(loc='upper left');

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

#must create dir in advance
savefig("figure/exercise_10.png", dpi=72)

show()

二.散點圖(scatter plots)

#!/usr/bin/env python
#encoding: utf-8

from pylab import *

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

axes([0.025, 0.025, 0.95, 0.95])
scatter(X, Y, s=75, c=T, alpha=.5)

xlim(-1.5, 1.5), xticks([])
ylim(-1.5, 1.5), yticks([])

savefig('figure/scatter_ex.png', dpi=48)
show()

三.等高線圖(contour plots)

#!/usr/bin/env python
#encoding: utf-8

from pylab import *

def f(x, y):
    return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

axes([0.025, 0.025, 0.95, 0.95])

contourf(X, Y, f(X,Y), 8, alpha=.75, cmap=cm.hot)
C = contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)
clabel(C, inline=1, fontsize=10)

xticks([])
yticks([])

savefig('figure/contour_ex.png', dpi=48)
show()

四.餅圖(Pie charts)

#!/usr/bin/env python
#encoding: utf-8

from pylab import *

n = 20
Z = np.ones(n)
Z[-1] *= 2

axes([0.025, 0.025, 0.95, 0.95])
pie(Z, explode=Z*.05, colors = ['%f' % (i/float(n)) for i in range(n)])
gca().set_aspect('equal')
xticks([])
yticks([])

savefig('figure/pie_ex.png', dpi=48)
show()


五.極軸圖

#!/usr/bin/env python
#encoding: utf-8

from pylab import *

ax = axes([0.025, 0.025, 0.95, 0.95], polar=True)

N = 20
theta = np.arange(0.0, 2*np.pi, 2*np.pi/N)
radii = 10*np.random.rand(N)
width = np.pi/4*np.random.rand(N)
bars = bar(theta, radii, width=width, bottom=0.0)

for r,bar in zip(radii, bars):
    bar.set_facecolor( cm.jet(r/10.))
    bar.set_alpha(0.5)

ax.set_xticklabels([])
ax.set_yticklabels([])

savefig('figure/polar_ex.png', dpi=48)
show()

六.三維繪圖

#!/usr/bin/env python
#encoding: utf-8

from pylab import *
from mpl_toolkits.mplot3d import Axes3D

fig = figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.hot)
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=cm.hot)
ax.set_zlim(-2, 2)

savefig('figure/plot3d_ex.png', dpi=48)
show()


七.數學公式

#!/usr/bin/env python
#encoding: utf-8

from pylab import *

eqs = []
eqs.append(r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2}\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1\sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$")
eqs.append(r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$")
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}}dx=\sqrt{\pi}$")
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")
eqs.append((r"$F_G = G\frac{m_1m_2}{r^2}$"))

axes([0.025, 0.025, 0.95, 0.95])

for i in range(24):
    index = np.random.randint(0, len(eqs))
    eq = eqs[index]
    size = np.random.uniform(12, 32)
    x, y = np.random.uniform(0, 1, 2)
    alpha = np.random.uniform(0.25, 0.75)
    text(x, y, eq, ha='center', va='center', color='#11557c', alpha=alpha, transform=gca().transAxes, fontsize=size,
            clip_on=True)

xticks([])
yticks([])

savefig('figure/text_ex.png', dpi=48)
show()

參考文獻

[1].http://reverland.org/python/2012/09/07/matplotlib-tutorial/