Matplotlib简介
Matplotlib是一个Python工具箱,用于科学计算的数据可视化。借助它,Python可以绘制如Matlab和Octave多种多样的数据图形。最初是模仿了Matlab图形命令, 但是与Matlab是相互独立的,通过Matplotlib中简单的接口可以快速的绘制2D图表
初试Matplotlib
Matplotlib中的pyplot子库提供了和matlab类似的绘图API.
import matplotlib.pyplot as plt #导入pyplot子库
plt.figure(figsize=(8, 4)) #创建一个绘图对象, 并设置对象的宽度和高度, 如果不创建直接调用plot, Matplotlib会直接创建一个绘图对象
plt.plot([1, 2, 3, 4]) #此处设置y的坐标为[1, 2, 3, 4], 则x的坐标默认为[0, 1, 2, 3]在绘图对象中进行绘图, 可以设置label, color和linewidth关键字参数
plt.ylabel('some numbers') #给y轴添加标签, 给x轴加标签用xlable
plt.title("hello"); #给2D图加标题
plt.show() #显示2D图
基础绘图
绘制折线图
与所选点的坐标有关
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
plt.plot(x, y, '-*r') # 虚线, 星点, 红色
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
多线图
只需要在plot函数中传入多对x-y坐标对就能画出多条线
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.plot(x, y, '--*r', x, z, '-.+g')
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("hello world")
plt.show()
柱状图
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.bar(x, y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()
子图
subplot()函数指明numrows行数, numcols列数, fignum图个数. 图的个数不能超过行数和列数之积
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
z = [1, 2, 3, 4, 5, 6]
plt.figure(1)
plt.subplot(211)
plt.plot(x, y, '-+b')
plt.subplot(212)
plt.plot(x, z, '-.*r')
plt.show()
文本添加
当需要在图片上调价文本时需要使用text()函数, 还有xlabel(), ylabel(), title()函数
text()函数返回matplotlib.text.Text, 函数详细解释
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = [0, 1, 2, 4, 5, 6]
y = [1, 2, 3, 2, 4, 1]
plt.plot(x, y, '-.*r')
plt.text(1, 2, "I'm a text") //前两个参数表示文本坐标, 第三个参数为要添加的文本
plt.show()
图例简介
legend()函数实现了图例功能, 他有两个参数, 第一个为样式对象, 第二个为描述字符
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])
plt.show()
或者调用set_label()添加图例
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
line, = plt.plot([1, 2, 3])
line.set_label("Label via method")
plt.legend()
plt.show()
同时对多条先添加图例
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
line1, = plt.plot([1, 2, 3])
line2, = plt.plot([3, 2, 1], '--b')
plt.legend((line1, line2), ('line1', 'line2'))
plt.show()
散点图和折线图是数据分析中最常用的两种图形。其中,折线图用于分析自变量和因变量之间的趋势关系,最适合用于显示随着时间而变化的连续数据,同时还可以看出数量的差异,增长情况。
Matplotlib 中绘制散点图的函数为 plot() ,使用语法如下:matplotlib.pyplot.plot
(*args, scalex=True, scaley=True, data=None, **kwargs)
常用参数及说明:
参数 | 接收值 | 说明 | 默认值 |
x,y | array | 表示 x 轴与 y 轴对应的数据; | 无 |
color | string | 表示折线的颜色; | None |
marker | string | 表示折线上数据点处的类型; | None |
linestyle | string | 表示折线的类型; | - |
linewidth | 数值 | 线条粗细:linewidth=1.=5.=0.3 | 1 |
alpha | 0~1之间的小数 | 表示点的透明度; | None |
label | string | 数据图例内容:label=‘实际数据' | None |
其他参数请参考文档:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html
基本用法
import pandas as pd
import matplotlib.pyplot as plt
#读取数据
datafile = u'D:\\pythondata\\learn\\matplotlib.xlsx'
data = pd.read_excel(datafile)
plt.figure(figsize=(10,5))#设置画布的尺寸
plt.title('Examples of line chart',fontsize=20)#标题,并设定字号大小
plt.xlabel(u'x-year',fontsize=14)#设置x轴,并设定字号大小
plt.ylabel(u'y-income',fontsize=14)#设置y轴,并设定字号大小
#color:颜色,linewidth:线宽,linestyle:线条类型,label:图例,marker:数据点的类型
plt.plot(data['时间'],data['收入_Jay'],color="deeppink",linewidth=2,linestyle=':',label='Jay income', marker='o')
plt.plot(data['时间'],data['收入_JJ'],color="darkblue",linewidth=1,linestyle='--',label='JJ income', marker='+')
plt.plot(data['时间'],data['收入_Jolin'],color="goldenrod",linewidth=1.5,linestyle='-',label='Jolon income', marker='*')
plt.legend(loc=2)#图例展示位置,数字代表第几象限
plt.show()#显示图像
在交互环境中查看帮助文档:
import matplotlib.pyplot as plt
help(plt.plot)
以下是对帮助文档重要部分的翻译:
plot函数的一般的调用形式:
#单条线:
plot([x], y, [fmt], data=None, **kwargs)
#多条线一起画
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
可选参数[fmt] 是一个字符串来定义图的基本属性如:颜色(color),点型(marker),线型(linestyle),
具体形式 fmt = '[color][marker][line]'
fmt接收的是每个属性的单个字母缩写,例如:
plot(x, y, 'bo-') # 蓝色圆点实线
若属性用的是全名则不能用*fmt*参数来组合赋值,应该用关键字参数对单个属性赋值如:
plot(x,y2,color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)
plot(x,y3,color='#900302',marker='+',linestyle='-')
常见的颜色参数:**Colors**
也可以对关键字参数color赋十六进制的RGB字符串如 color='#900302'
============= ===============================
character color
============= ===============================
``'b'`` blue 蓝
``'g'`` green 绿
``'r'`` red 红
``'c'`` cyan 蓝绿
``'m'`` magenta 洋红
``'y'`` yellow 黄
``'k'`` black 黑
``'w'`` white 白
============= ===============================
点型参数**Markers**,如:marker='+' 这个只有简写,英文描述不被识别
============= ===============================
character description
============= ===============================
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'s'`` square marker
``'p'`` pentagon marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
============= ===============================
线型参数**Line Styles**,linestyle='-'
============= ===============================
character description
============= ===============================
``'-'`` solid line style 实线
``'--'`` dashed line style 虚线
``'-.'`` dash-dot line style 点画线
``':'`` dotted line style 点线
============= ===============================
以下三个样例转载于
样例1
函数原型:matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
>>> plot('xlabel', 'ylabel', data=obj)
解释:All indexable objects are supported. This could e.g. be a dict, a pandas.DataFame or a structured numpy array.
data 参数接受一个对象数据类型,所有可被索引的对象都支持,如 dict 等
import matplotlib.pyplot as plt
import numpy as np
'''read file
fin=open("para.txt")
a=[]
for i in fin:
a.append(float(i.strip()))
a=np.array(a)
a=a.reshape(9,3)
'''
a=np.random.random((9,3))*2 #随机生成y
y1=a[0:,0]
y2=a[0:,1]
y3=a[0:,2]
x=np.arange(1,10)
ax = plt.subplot(111)
width=10
hight=3
ax.arrow(0,0,0,hight,width=0.01,head_width=0.1, head_length=0.3,length_includes_head=True,fc='k',ec='k')
ax.arrow(0,0,width,0,width=0.01,head_width=0.1, head_length=0.3,length_includes_head=True,fc='k',ec='k')
ax.axes.set_xlim(-0.5,width+0.2)
ax.axes.set_ylim(-0.5,hight+0.2)
plotdict = { 'dx': x, 'dy': y1 }
ax.plot('dx','dy','bD-',data=plotdict)
ax.plot(x,y2,'r^-')
ax.plot(x,y3,color='#900302',marker='*',linestyle='-')
plt.show()
样例2,
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 2*np.pi, 0.02)
y = np.sin(x)
y1 = np.sin(2*x)
y2 = np.sin(3*x)
ym1 = np.ma.masked_where(y1 > 0.5, y1)
ym2 = np.ma.masked_where(y2 < -0.5, y2)
lines = plt.plot(x, y, x, ym1, x, ym2, 'o')
#设置线的属性
plt.setp(lines[0], linewidth=1)
plt.setp(lines[1], linewidth=2)
plt.setp(lines[2], linestyle='-',marker='^',markersize=4)
#线的标签
plt.legend(('No mask', 'Masked if > 0.5', 'Masked if < -0.5'), loc='upper right')
plt.title('Masked line demo')
plt.show()
例3 :圆
import numpy as np
import matplotlib.pyplot as plt
theta = np.arange(0, 2*np.pi, 0.01)
xx = [1,2,3,10,15,8]
yy = [1,-1,0,0,7,0]
rr = [7,7,3,6,9,9]
fig = plt.figure()
axes = flg.add_subplot(111)
i = 0
while i < len(xx):
x = xx[i] + rr[i] *np.cos(theta)
x = xx[i] + rr[i] *np.cos(theta)
axes.plot(x,y)
axes.plot(xx[i], yy[i], color='#900302', marker='*')
i = i+1
width = 20
hight = 20
axes.arrow(0,0,0,hight,width=0.01,head_width=0.1,head_length=0.3,fc='k',ec='k')
axes.arrow(0,0,width,0,width=0.01,head_width=0.1,head_length=0.3,fc='k',ec='k')
plt.show()