1、介绍
把每个图都看作一个对象,图中的每一个部分也是对象。——所有的一切都是对象。
工具——ipython notebook
是python里边用的最多的2D&3D的会图库,开源免费库,使用方法和matlab类似
是一个网页版的ipython,可以利用网页的特性展现一些副文本。
网络版的:https://try.jupyter.org/
打开之后如下图所示:
点击右上角new,然后选择python2
输入程序即可。
用它就可以不用安装各种库啊啥的,只要有一个浏览器就可以了。还可以写笔记。还可以放在github上。
作者例子:http://github.com/heibanke/math/blob/master/matplotlib_0ipynb
本地安装的话:pip install ipython[notebook]
安装完之后敲:ipython notebook之后就自动启动了,然后自动打开浏览器
如果觉着安装各种库比较费劲的话,可以安装集成开发环境:Anaconda
2、画简单图
如何打开ipynb的文件呢?
选择打开方式——在问价夹下C:\Portable Python 2.7.6.1\App\Scriptsjupyter-notebook.exe——选择jupyter-notebook.exe打开
打开之后是浏览器的形式
%matplotlib inline是用来确定matplotlib的输出方式,这样的话,就不用再新弹出一个窗口来输出图像,而是直接输出到网页里。
2.1画简单图
运行时shift+回车键
from matplotlib import pyplot as plt x = [1,2,3,1]
y = [1,3,0,1] plt.plot(x,y) #plt.title('Triangle')
#plt.ylabel('Y axis')
#plt.xlabel('X axis') #plt.xticks([1,6])
#plt.yticks([1,6])
#plt.xticks([1,6],['a','b']) #plt.ylim([-1,4])
#plt.xlim([-1,4]) plt.grid(True,color='r') plt.show()
2.2画图的样式
数据线的样式设置
颜色缩写 全称
b blue
c cyan
g gree
k black
m magenta
r red
w white
y yellow
线型缩写 含义
-- --虚线
-. -.虚线
: .虚线
- 实线
marker类型参考
http://www.labri.fr/perso/nrougier/teaching/matplotlib/#line-properties
from matplotlib import pyplot as plt
import numpy as np x = [1,2,3,1]
y = [1,3,0,1] # np.array将列表转换成numpy的数组后可以支持广播broadcast运算
plt.plot(x,y,color='r',linewidth='',linestyle='--',marker='D', label='one')
plt.plot(np.array(x)+1,np.array(y)+1,color='g',linewidth='',linestyle=':',marker='o', label='two')
plt.plot(np.array(x)+2,np.array(y)+3,color='k',linewidth='',linestyle='-.',marker='>', label='three') plt.grid(True)
plt.legend()
#plt.legend(loc='upper left') plt.show()
2.3中文
- 下载参考资料里的微软雅黑字体msyh.ttf
- 将字体拷贝到matplotlib安装位置 /matplotlib/mpl-data/fonts/
-
修改配置文件 /matplotlib/mpl-data/matplotlibrc
1) backend : TkAgg #mac需要修改,windows默认就是TkAgg
2) font.family : Microsoft YaHei
3) font.serif : Microsoft YaHei, ......#(后面的不变,只在前面加雅黑字体)
OK, 大功告成,试试效果吧
# -*- coding: utf-8 -*-
from matplotlib import pyplot as plt
import numpy as np x = [1,2,3,1]
y = [1,3,0,1] x2 = np.array(x)+1
y2 = np.array(y)+1 plt.plot(x,y,'g',label=u'第一个', linewidth=5)
plt.plot(x2,y2,'c',label=u'第二个',linewidth=5) plt.title(u'两个三角形')
plt.ylabel(u'Y轴')
plt.xlabel(u'X轴') plt.legend() plt.show()
2.4公式
import matplotlib.pyplot as plt
fig = plt.figure() #figsize=(10,6)
ax= fig.add_subplot(111)
ax.set_xlim([1, 6]);
ax.set_ylim([1, 9]);
ax.text(2, 8, r"$ \mu \alpha \tau \pi \lambda \omega \tau \
lambda \iota \beta $",color='r',fontsize=20);
ax.text(2, 6, r"$ \lim_{x \rightarrow 0} \frac{1}{x} $",fontsize=20);
ax.text(2, 4, r"$ a \ \leq \ b \ \leq \ c \ \Rightarrow \ a \
\leq \ c$",fontsize=20);
ax.text(2, 2, r"$ \sum_{i=1}^{\infty}\ x_i^2$",fontsize=20);
ax.text(4, 8, r"$ \sin(0) = \cos(\frac{\pi}{2})$",fontsize=20);
ax.text(4, 6, r"$ \sqrt[3]{x} = \sqrt{y}$",fontsize=20);
ax.text(4, 4, r"$ \neg (a \wedge b) \Leftrightarrow \neg a \
\vee \neg b$");
ax.text(4, 2, r"$ \int_a^b f(x)dx$",fontsize=20);
plt.show()
Annotate各种格式可参考文档
http://matplotlib.org/users/annotations_guide.html#annotating-with-arrow
import matplotlib.pyplot as plt plt.figure(1, figsize=(3,3))
ax = plt.subplot(111) ann = ax.annotate("Test",
xy=(0.2, 0.2),
xytext=(0.8, 0.8),
size=20, va="center", ha="center",
bbox=dict(boxstyle="round4", fc="w"),
arrowprops=dict(arrowstyle="-|>",
connectionstyle="arc3,rad=0.2",
fc="r"),
)
ax.grid(True)
plt.show()
具体设计成什么样子需要查一下官方文档
2.5多子图结构
from matplotlib import pyplot as plt
import numpy as np # arange类似python里的range
t = np.arange(0, 5, 0.2) fig = plt.figure()#figsize=(10,6) #行, 列, 序号
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(212) ax1.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
ax1.grid(True)
ax1.set_title('plot') ax2.semilogy(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
ax2.grid(True)
ax2.set_title('ylog') ax3.loglog(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
ax3.grid(True)
ax3.set_title('loglog') fig.suptitle('normal vs ylog vs loglog')
#fig.subplots_adjust(hspace=0.4) plt.show()
3深度图
图是用来更好的解释数据
目标:让老板或客户印象深刻,一目了然
1. 饼状图
2. 柱状图
3. 散点图
4. 概率图
5. 组合图
6. 三维数据图
7. 美化
3.1饼状图
import matplotlib.pyplot as plt plt.figure(figsize=(9,6)) # The slices will be ordered and plotted counter-clockwise.
labels = [u'直接访问', u'外部链接', u'搜索引擎']
sizes = [160, 130, 110]
colors = ['yellowgreen', 'gold', 'lightskyblue'] #explode 爆炸出来
explode = (0.05, 0.0, 0.0) patches, l_texts, p_texts = plt.pie(sizes, explode=explode, labels=labels, colors=colors, labeldistance=0.8,
autopct='%3.1f%%', shadow=True, startangle=90, pctdistance=0.6) # 设置x,y轴刻度一致,这样饼图才能是圆的
#plt.axis('equal')
#plt.legend() """
for t in l_texts:
t.set_size(20) for t in p_texts:
t.set_size(20)
"""
plt.show()
3.2柱状图
import numpy as np
from matplotlib import pyplot as plt plt.figure(figsize=(9,6)) n = 12
X = np.arange(n)+1
# numpy.random.uniform(low=0.0, high=1.0, size=None), normal
Y1 = (1-X/float(n+1)) * np.random.uniform(0.5,1.0,n)
Y2 = (1-X/float(n+1)) * np.random.uniform(0.5,1.0,n) # bar and barh
width = 0.5
plt.bar(X, Y1, width=width, facecolor='#9999ff', edgecolor='white')
#plt.bar(X, -Y2, width=width, facecolor='#ff9999', edgecolor='white') """
for x,y in zip(X,Y1):
plt.text(x+0.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom') for x,y in zip(X,-Y2):
plt.text(x+0.4, y-0.15, '%.2f' % y, ha='center', va= 'bottom')
""" #plt.ylim(-1.25,+1.25)
plt.show()
3.3散点图
from matplotlib import pyplot as plt
import numpy as np plt.figure(figsize=(9,6)) n = 1024 # rand 和 randn
X = np.random.randn(1,n)
Y = np.random.randn(1,n) T = np.arctan2(Y,X) plt.scatter(X,Y, s=75, c=T, alpha=.4, marker='o') #plt.xlim(-1.5,1.5), plt.xticks([])
#plt.ylim(-1.5,1.5), plt.yticks([]) plt.show()
3.4概率分布
from matplotlib import pyplot as plt
import numpy as np mu = 0
sigma = 1
x = mu + sigma*np.random.randn(10000) fig,(ax0,ax1)=plt.subplots(ncols=2, figsize=(9,6)) ax0.hist(x, 20, normed=1, histtype='bar', facecolor='g', alpha=0.75)
ax0.set_title('pdf') ax1.hist(x, 20, normed=1, histtype='bar', rwidth=0.8, cumulative=True)
ax1.set_title('cdf') plt.show()
3.5组合图
# ref : http://matplotlib.org/examples/pylab_examples/scatter_hist.html import numpy as np
import matplotlib.pyplot as plt # the random data
x = np.random.randn(1000)
y = np.random.randn(1000) # 定义子图区域
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02 rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height] plt.figure(1, figsize=(6, 6)) # 根据子图区域来生成子图
axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy) # no labels
#axHistx.xaxis.set_ticks([])
#axHisty.yaxis.set_ticks([]) # now determine nice limits by hand:
N_bins=20
xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))])
binwidth = xymax/N_bins
lim = (int(xymax/binwidth) + 1) * binwidth
nlim = -lim # 画散点图,概率分布图
axScatter.scatter(x, y)
axScatter.set_xlim((nlim, lim))
axScatter.set_ylim((nlim, lim)) bins = np.arange(nlim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal') # 共享刻度
axHistx.set_xlim(axScatter.get_xlim())
axHisty.set_ylim(axScatter.get_ylim()) plt.show()
# ref http://matplotlib.org/examples/showcase/integral_demo.html
import numpy as np
import matplotlib.pyplot as plt def func(x):
return (x - 3) * (x - 5) * (x - 7) + 85 a, b = 2, 9 # integral limits
x = np.linspace(0, 10)
y = func(x) # 画线
fig, ax = plt.subplots()
plt.plot(x, y, 'r', linewidth=2)
plt.ylim(ymin=0) # 画阴影区域
xf = x[np.where((x>a)&(x<b))]
plt.fill_between(xf, np.zeros(len(xf)), func(xf), color='blue', alpha=.25) # 画文本
plt.text(0.5 * (a + b), 30, r"$\int_a^b f(x)\mathrm{d}x$",
horizontalalignment='center', fontsize=20) plt.show()
3.6三维数据图
import numpy as np
import matplotlib.pyplot as plt fig = plt.figure(figsize=(9,6),facecolor='white') # Number of ring
n = 50
size_min = 50
size_max = 50*50 # Ring position
P = np.random.rand(n,2) # Ring colors R,G,B,A
C = np.ones((n,4)) * (0,0,0,1)
# Alpha color 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
plt.scatter(P[:,0], P[:,1], s=S, lw = 0.5,
edgecolors = C, facecolors='None') plt.xlim(0,1), plt.xticks([])
plt.ylim(0,1), plt.yticks([]) plt.show()
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt fig = plt.figure(figsize=(9,6))
ax = fig.add_subplot(111,projection='3d') z = np.linspace(0, 6, 1000)
r = 1
x = r * np.sin(np.pi*2*z)
y = r * np.cos(np.pi*2*z) ax.plot(x, y, z, label=u'螺旋线', c='r')
ax.legend() # dpi每英寸长度的点数
plt.savefig('3d_fig.png',dpi=200)
plt.show()
3d画图种类很多,可参考:http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html
其他种类图可参考:http://matplotlib.org/gallery.html