Iptyhon的%魔术命令
%magic 显示所有的命令
%hist 显示ipython命令的输入历史
%pdb 异常发生后自动进入调试器
%reset 删除当前命·名空间中的全部变量或名称
%who 显示Ipython当前命名空间已经定义的变量
%time statement 给出代码的执行时间,statement表示一段代码
%timeit statement 多次执行代码,计算综合平均执行时间
#Numpy
##列表和数组
###区别
列表:数据类型可以不同
数组:数据类型相同
#Numpy库
应用:
import numpy as np
计算 A^2 +B^3
def pySum():
a = [0, 1, 2, 3, 4]
b = [9, 8, 7, 6, 5]
c=[]
for i in range(len(a)):
c.append(a[i]**2 + b[i]**3)
return c
print(pySum())
输出结果:
[729, 513, 347, 225, 141]
#Numpy 的数组对象 ndarray:
import numpy as np
def npSum():
a = np.array([0, 1, 2, 3, 4])
b = np.array([9, 8, 7, 6, 5])
c= a**2 + b**3
return c
print(npSum())
输出结果:
[729 513 347 225 141]
轴:axis
#ndarray对象的属性
.ndim 秩,即轴的数量或维度的数量
.shape ndarray 对象的尺度,对于矩阵,n行m列
.size ndarray 对象的元素个数,相当于.shape中n*m的值
.dtype ndarray 对象的元素类型
.itemsize ndarray对象中每个元素的大小,以字节为单位
#e.g
a = np.array([[0, 1, 2, 3, 4],[9, 8, 7, 6, 5]])
print(a.ndim)
2
print(a.shape)
(2,5)
print(a.size)
10
print(a.dtype)
int32
print(a.itemsize)
4
#ndarray 数组的创建方法
(1):用列表,元组等类型创建ndarray数组
x = np.array(list/tuple)
x = np.araay(list/tuple,dtype = np.float32)
x = np.array([0, 1, 2, 3])
print(x)
[0 1 2 3]
x = np.array((4, 5, 6, 7))
print(x)
[4 5 6 7]
x = np.array([[1, 2],[3, 4],[5,6]])
print(x)
[[1 2]
[3 4]
[5 6]]
(2):使用Numpy中函数创建ndarray数组;
np.arange(n) 类似range()函数,返回ndarray类型,元素从0 - 1
np.ones(shape) 根据shape生成一个全为1数组,shape为元组类型
np.zeros(shape) 根据shape生成一个全为0数组
np.full(shape, val) 根据shape生成一个数组,每个元素都是val
np.eye(n) 创建一个阶为n的单位矩阵
np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.ones((3,5))
array([[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.]])
np.zeros((3, 5))
array([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])
np.eye(3)
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
np.full((3,5), 3)
Out[30]:
array([[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3],
[3, 3, 3, 3, 3]])
n = np.ones((2, 3, 4))
print(n)
[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]
n.shape
(2, 3, 4)
np.ones_like(a) 根据数组a的形状生成全为1的数组
np.zeros_like(a) 根据数组a的形状生成全为0的数组
np.full_like(a,val) 根据数组a的形状生成全为val的数组
np.linspace() 根据起始数据等间距填充数据,形成数组
np.concatenate() 将两个或多个数组合并成一个数组
a = np.linspace(1, 10, 4)
print(a)
[ 1. 4. 7. 10.]
b = np.linspace(1, 10, 4, endpoint = False)# 加上endpoint = False 末位置将不会出现10
print(b)
[1. 3.25 5.5 7.75]
c = np.concatenate((a,b))
print(c)
[ 1. 5.5 10. 1. 3.25 5.5 7.75]
#ndarray数组的变换
ndarray数组变换的函数
.reshape(shape) 不改变数组元素,返回一个shape形状的数组,原数组不变
.resize(shape) 与.reshape()功能相同,但是修改原数组
.swapaxes(ax1, ax2) 将数组n个维度中两个维度进行调换
.flatten() 将数组进行降维,返回折叠后的一维数组,原数组不变
a = np.ones((2, 3, 4), dtype = np.int32)
print(a)
[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]
a.reshape((3, 8))
array([[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1]])
a.resize((3,8))
print(a)
[[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]
[1 1 1 1 1 1 1 1]]
a.flatten()
Out[45]:
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1])
##new_a = a.astype(new_type)
a = np.ones((2, 3, 4),dtype = np.int)
print(a)
[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]
b = a.astype(np.float)
print(b)
[[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]]
ndarray数组向列表的转换
ls = a.tolist()
a = np.full((2, 3, 4), 25, dtype = np.int32)
print(a)
[[[25 25 25 25]
[25 25 25 25]
[25 25 25 25]]
[[25 25 25 25]
[25 25 25 25]
[25 25 25 25]]]
a.tolist()
[[[25, 25, 25, 25], [25, 25, 25, 25], [25, 25, 25, 25]],
[[25, 25, 25, 25], [25, 25, 25, 25], [25, 25, 25, 25]]]
#ndarray数组的操作
##数组的索引和切片
import numpy as np
a = np.array([9, 8, 7, 6, 5])
print(a[2])
7
print(a[1: 4: 2])
[8 6]
a = np.arange(24).reshape((2, 3, 4))
print(a)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
print(a[1, 2, 3]) # 1 代表第二个列表
23
print(a[0, 1, 2])
6
print(a[-1, -2, -3])
17
print(a[:,1, -3])
[ 5 17]
print(a[:, 1:3, :])
[[[ 4 5 6 7]
[ 8 9 10 11]]
[[16 17 18 19]
[20 21 22 23]]]
print(a[:, :,::2]) # 2代表跨度
[[[ 0 2]
[ 4 6]
[ 8 10]]
[[12 14]
[16 18]
[20 22]]]
###average value
a = a.mean()
print(a)
[[[0. 0.08695652 0.17391304 0.26086957]
[0.34782609 0.43478261 0.52173913 0.60869565]
[0.69565217 0.7826087 0.86956522 0.95652174]]
[[1.04347826 1.13043478 1.2173913 1.30434783]
[1.39130435 1.47826087 1.56521739 1.65217391]
[1.73913043 1.82608696 1.91304348 2. ]]]
##ndarray 数据执行运算函数
np.abs(x) np.fabs(x) 计算数组各元素的绝对值
np.sqrt(x) 计算数组各元素的平方根
np.square(x) 计算数组各元素的平方
np.log(x) np.log10(x) np.log2(x) 计算数组各元素的自然对数,以10和2为底的对数
np.ceil(x) np.floor(x) 计算数组各元素的ceiling值或者floor值(ceiling 天花板 floor 地板)
np.rint(x) 计算数组各元素的四舍五入
np.modf(x) 将数组各元素的小数和整数部分以独立数组形式返回
np.cos(x) np.cosh(x) np.sin(x) np.sinh(x) np.tan(x) np.tanh(x)
计算数组个元素的普通型和双曲面三角函数
np.exp(x) 计算数组个元素的指数值
np.sign(x) 计算数组各元素的符号值(1(+),0,-1(-))
#numpy数据存取函数
##1.CSV文件提取
CSV 是一种常见文件格式,用来存储批量数据(数据之间用逗号隔开)
np.savetxt(frame, array, fmt= ‘%.18e’, delimiter = None) # 写
frame:文件,字符串,可以是.az或.ba2的压缩文件
array:存入文件的数组
fmt:写入文件的格式,例如:%d %.2f %18e
delimiter:分割字符串,默认是空格,一般设置成逗号。
import numpy as np
a = np.arange(100).reshape(5, 20)
np.savetxt("a.csv", a ,fmt ="%d", delimiter = ",")
np.loadtxt(frame, dtype = np.float, delimiter = None, unpack = False) # 读
frame:文件,字符串,可以是.gz或.bz2的压缩文件
dtype: 数据类型,将文件元素,转化成指定的类型。
delimiter: 分割字符串,默认是空格。
unpack: 如果True ,读入属性将分别写入不同变量。False写入同一个数组
b = np.loadtxt("a.csv", delimiter = ",")
print(b)
result:
[[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17.
18. 19.]
[20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37.
38. 39.]
[40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57.
58. 59.]
[60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77.
78. 79.]
[80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97.
98. 99.]]
设置成int类型
c = np.loadtxt("a.csv", dtype = np.int, delimiter = ",")
print(c)
result
[[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
[20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39]
[40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59]
[60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79]
[80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]]
np.savetxt(), np.loadtxt()只能保存一维或者二维数据
下面是多维数据格式
a.tofile(frame,sep="",format="%s") # 写
a = np.arange(100).reshape(5,10, 2)
a.tofile("b.dat", sep= ",", format ="%d")
不设置分隔符的话,文件打开将会是二进制格式
a = np.arange(100).reshape(5, 10, 2)
a.tofile("b.dat", format = "%d")
np.fromfile(frame, dtype = float, count = -1, sep = “”) #读
frame: 文件,字符串。
dtype: 读取文件的数据类型。默认为float;
count: 读入元素个数, -1表示读入整个文件,想读入指定数量的话可以设置。
sep:数据分割字符串,如果是空串,写入文件为二进制。
a = np.arange(100).reshape(5, 10, 2)
a.tofile("b.dat", sep =",",format = "%d")
c = np.fromfile("b.dat", dtype = np.int, sep = ",")
print(c)
result
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
96 97 98 99]
c = np.fromfile("b.dat", dtype = np.int, sep = ",").reshape(5, 10, 2)
print(c)
result
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]
[[20 21]
[22 23]
[24 25]
[26 27]
[28 29]
[30 31]
[32 33]
[34 35]
[36 37]
[38 39]]
[[40 41]
[42 43]
[44 45]
[46 47]
[48 49]
[50 51]
[52 53]
[54 55]
[56 57]
[58 59]]
[[60 61]
[62 63]
[64 65]
[66 67]
[68 69]
[70 71]
[72 73]
[74 75]
[76 77]
[78 79]]
[[80 81]
[82 83]
[84 85]
[86 87]
[88 89]
[90 91]
[92 93]
[94 95]
[96 97]
[98 99]]]
Numpy的编写文件存取
np.save(fname, array) 或 np.savez(frame, array)
fname:文件名,以.npy为扩展名,压缩扩展名为.npz
array:数组变量
np.load(fname)
fname:文件名,以.npy为扩展名压缩扩展名为.npz
a = np.arange(100).reshape(5, 10, 2)
np.save("a.npy", a)
b = np.load("a.npy")
print(b)
result
[[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
[14 15]
[16 17]
[18 19]]
[[20 21]
[22 23]
[24 25]
[26 27]
[28 29]
[30 31]
[32 33]
[34 35]
[36 37]
[38 39]]
[[40 41]
[42 43]
[44 45]
[46 47]
[48 49]
[50 51]
[52 53]
[54 55]
[56 57]
[58 59]]
[[60 61]
[62 63]
[64 65]
[66 67]
[68 69]
[70 71]
[72 73]
[74 75]
[76 77]
[78 79]]
[[80 81]
[82 83]
[84 85]
[86 87]
[88 89]
[90 91]
[92 93]
[94 95]
[96 97]
[98 99]]]
##NumPy的随机数函数字库
NumPy的random字库
基本的四个函数
rand(d0,d1,…,dn) 根据d0-dn创建随机数数组,浮点数,[0,1],均匀分布
randn(d0,d1,…,dn) 根据d0-dn穿件随机数数组,标准正态分布
randint(low[,high,shape]) 根据shape创建随机数组
#np.random的统计函数
sum(a, axis = None) 根据定轴axis计算数组a相关元素之和,axis整数或元组
mean(a, axis = None) 根据定轴axis计算数组a相关元素的期望,axis整数或元组
average(a, axis = None, weights = None) 根据给定轴axis计算a 相关元素的加权平均值
std(a, axis = None) 根据定轴axis计算数组a相关元素的标准差
var(a, axis = None) 根据定轴axis计算数组a相关元素的方差
import numpy as np
a = np.arange(15).reshape(3,5)
print(a)
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
np.sum(a)
np.mean(a, axis = 1) # 计算二维的行
array([ 2., 7., 12.])
np.mean(a,axis = 0) # 计算二维的列
array([5., 6., 7., 8., 9.])
np.average(a,axis = 0,weights = [10,5, 1])
array([2.1875, 3.1875, 4.1875, 5.1875, 6.1875])
np.std(a)
4.320493798938574
np.var(a)
18.666666666666668
#np.random的统计函数2
min(a) max(a) 计算数组a中元素的最小值,最大值
argmin(a) argmax(a) 计算数组a中元素的最小值,最大值的降一维后下标
unravel_index(index,shape) 根据shape将下一维下标index转换成多维下标
ptp(a) 计算数组a中元素最大值与最小值的差
median(a) 计算数组a中元素的中位数
import numpy as np
b = np.arange(15, 0,-1).reshape(3,5)
print(b)
[[15 14 13 12 11]
[10 9 8 7 6]
[ 5 4 3 2 1]]
np.max(b)
15
np.argmax(b)
0
np.unravel_index(np.argmax(b),b.shape)
(0, 0)
np.ptp(b)
14
np.median(b)
8.0
#np.random的梯度函数
np.gradient(f) 计算数组f中元素的梯度,当f为多维时,返回每个维度的梯度
XY坐标轴连续三个X坐标对应的Y轴值:a,b,c
b的梯度是:(c-a)/2
import numpy as np
a = np.random.randint(0,20,(5))
print(a)
[ 1 0 16 7 1]
np.gradient(a) # 如果是最左边第2个值减去第1个值,最右边类推,中间的等于右边减去左边除二
array([-1. , 7.5, 3.5, -7.5, -6. ])
b = np.random.randint(0,20,(5))
print(b)
[ 9 16 2 1 3]
np.gradient(b)
array([ 7. , -3.5, -7.5, 0.5, 2. ])
c = np.random.randint(0,50,(3,5))
print(c)
[[ 5 37 48 38 29]
[ 3 11 45 40 14]
[33 9 5 10 19]]
np.gradient(c) # 一个行一个列
[array([[ -2. , -26. , -3. , 2. , -15. ],
[ 14. , -14. , -21.5, -14. , -5. ],
[ 30. , -2. , -40. , -30. , 5. ]]),
array([[ 32. , 21.5, 0.5, -9.5, -9. ],
[ 8. , 21. , 14.5, -15.5, -26. ],
[-24. , -14. , 0.5, 7. , 9. ]])]
#PIL库
PIL , Python Image Library
PIL库是一个具有强大图像处理能力的第三方库
引用方法:
from PIL import Image
from PIL import Image
import numpy as np
im = np.array(Image.open("D://PythonDemo//MySomeTest//chinamap.jpg"))
print(im.shape, im.dtype)
(484, 500, 3) uint8
from PIL import Image
import numpy as np
a= np.array(Image.open("D://PythonDemo//MySomeTest//chinamap.jpg"))
print(a.shape,a.dtype) #484,500代表长宽
(484, 500, 3) uint8
b = [255,255,255]-a # 颜色翻转,灰度
im = Image.fromarray(b.astype("uint8"))
im.save("D://PythonDemo//MySomeTest//chinamap1.jpg")
from PIL import Image
import numpy as np
a = np.array(Image.open("D://PythonDemo//MySomeTest//chinamap.jpg").convert("L")) #L代表灰度
b = 255 -a
im = Image.fromarray(b.astype("uint8"))
im.save("D://PythonDemo//MySomeTest//chinamap2.jpg")
区间转换
from PIL import Image
import numpy as np
a = np.array(Image.open("D://PythonDemo//MySomeTest//chinamap.jpg").convert("L"))
c = (100/255)*a +150 # 区间变换
im = Image.fromarray(c.astype("uint8"))
im.save("D://PythonDemo//MySomeTest//chinamap3.jpg")
matplotlib
一个简单的实现
import matplotlib.pyplot as plt
plt.plot([3, 1, 4, 5, 2]) # y轴的值
plt.ylabel("grade")
# plt.savefig("testV1", dpi = 600) #保存文件,格式默认.png dpi.代表质量
plt.show()
result:
test 2
import matplotlib.pyplot as plt
plt.plot([0, 2, 4, 6, 8], [3, 1, 4, 5, 2]) # 设置点
plt.ylabel("Grade")
plt.axis([-1, 10, 0, 6]) # 分别设置x,y轴的取值范围
plt.show()
result:
Pyplot
plt.subplot(nrows, ncols, plot_numer)
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t)*np.cos(2*np.pi*t)
a = np.arange(0.0, 5.0, 0.02)
plt.subplot(211)
plt.plot(a, f(a))
plt.subplot(212)
plt.plot(a, np.cos(a*8))
plt.savefig("testV3", dpi=600)
plt.show()
**plt.plot(x, y, format_string, kwargs)
x:X轴数据,列表或数组,可选
y:Y轴数据,列表或数组
format_string: 控制曲线的格式字符串,可选。
**kwargs:第二组或更多(x, y, format_string)
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(10)
plt.plot(a, a*1.5, a, a*2.5, a, a*3.5, a, a*4.5)
plt.savefig("testV4", dpi=600)
plt.show()
result:
format_string:
控制曲线的格式字符串,可选,由颜色字符,风格字符和标记字符组成
颜色字符
颜色字符 | 说明 |
---|---|
‘b’’ | 蓝色 |
‘g’ | 绿色 |
‘r’ | 红色 |
‘c’ | 青绿色 |
‘m’ | 洋红色 |
‘y’ | 黄色 |
‘k’ | 黑色 |
‘w’ | 白色 |
0.8 | 灰度值字符串 |
‘#008000’ | GRB颜色 |
风格字符
风格字符 | 说明 |
---|---|
‘-’ | 实线 |
‘–’’ | 破折线 |
‘-.’ | 电话线 |
‘:’ | 虚线 |
‘’‘’ | 无线条 |
标记字符
标记字符 | 说明 |
---|---|
‘.’ | 点标记 |
‘,’ | 像素标记(极小点) |
‘o’ | 实心圈标记 |
‘v’ | 倒三角标记 |
‘^’ | 上三角标记 |
‘>’ | 右三角标记 |
'<’ | 左三角标记 |
‘1’ | 下花三角标记 |
‘2’ | 上花三角标记 |
‘3’ | 左花三角标记 |
‘4’ | 右花三角标记 |
‘s’ | 实心方形标记 |
‘p’ | 实心五角标记 |
‘*’ | 星型标记 |
‘h’ | 竖六边形标记 |
‘H’ | 横六边形标记 |
‘+’ | 十字标记 |
‘x’ | x标记 |
‘D’ | 菱形标记 |
‘d’ | 瘦菱形标记 |
竖线 | 垂直线标记 |
for example:
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(10)
plt.plot(a, a*1.5, 'go-', a, a*2.5, 'rx', a, a*3.5, '*', a, a*4.5, 'b-.')
plt.savefig("testV5", dpi=600)
plt.show()
result:
kwargs
color: 控制颜色,color = “blue”
linestyle: 线条风格,linestyle = "dashed’
marker: 标记风格,marker = ‘o’
markerfaceolor: 标记颜色,markerfacecolor = ‘blue’
markersize: 标记尺寸,markersize = 20
pyplot中文显示
第一种方法,reParams修改
rcParams的属性
属性 | 说明 |
---|---|
‘font.family’ | 用于显示字体的名字 |
‘font.style’ | 字体风格,正常’normal’,或斜体’italic’ |
‘font.size’ | 字体大小,整数字号或者’large’,‘x-small’ |
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei' # SimHei 是黑体
plt.plot([3, 1, 4, 5, 2])
plt.ylabel("纵轴")
plt.savefig("testV6", dpi=600)
plt.show()
result:
中文字体
rcParams[‘font.family’]
中文字体 | 说明 |
---|---|
‘SimHei’ | 中文黑体 |
‘Kaiti’ | 中文楷体 |
‘LiSu’ | 中文隶书 |
‘FangSong’ | 仿宋 |
‘YouYuan’ | 中文幼圆 |
‘STSong’ | 华文宋体 |
(1)下面的是全局的字体改变(不建议使用)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'STSong'
matplotlib.rcParams['font.size'] = 20
a = np.arange(0.0, 5.0, 0.02)
plt.xlabel("横轴:时间")
plt.ylabel("纵轴:振幅")
plt.plot(a, np.cos(2*np.pi*a), 'r--')
plt.savefig("testV7", dpi=200)
plt.show()
result:
(2)局部出现中文.
fontproperties:
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(0.0, 5.0, 0.02)
plt.xlabel("横轴:时间", fontproperties="SimHei", fontsize=20)
plt.ylabel("纵轴:振幅", fontproperties="Simhei", fontsize=20)
plt.plot(a, np.cos(2*np.pi*a), 'r--')
plt.show()
result:
运行结果和上图一样
pyplot的文本显示函数
函数 | 说明 |
---|---|
plt.xlabel | 对X轴增加文本标签 |
plt.ylabel | 对Y轴增加文本标签 |
plt.title | 对图形整体增加文本标签 |
plt.text | 在任意位置增加文本 |
plt.annotate(注释) | 在图形中增加带箭头的注解 |
import numpy as np
import matplotlib.pyplot as plt
a = np.arange(0.0, 5.0, 0.02)
plt.plot(a, np.cos(2*np.pi*a), 'r--')
plt.xlabel("横轴:时间", fontproperties="SimHei", fontsize=20, color="green")
plt.ylabel("纵轴:振幅", fontproperties="SimHei", fontsize=20, color="purple")
plt.title("正弦值$y=cos(2\pi x)$", fontproperties="SimHei", fontsize=25)
plt.text(2, 1, r'$\mu=100$',fontsize=15) # (2,1)代表横纵坐标
plt.axis([-1, 6, -2, 2])
plt.grid(True) # 网格
plt.savefig("testV9", dpi=200)
plt.show()
result:
子图
plt.subplot2grid()
plt.subplot2grid(GridSpace, CurSpec, colspan = 1, rowspan = 1)
GridSpace: 元组,将空间分为mxn块
CurSpe: 元组, 行列
colspan: 在行上延长
rowspan:在列上延长
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :-1])
ax3 = plt.subplot(gs[1:, -1])
ax4 = plt.subplot(gs[2, 0])
ax5 = plt.subplot(gs[2, 1])
plt.savefig("testV10", dpi=100)
plt.show()
result:
pyplot的基础图标函数
函数 | 说明 |
---|---|
plt.plot(x, y, fmt…) | 绘制一个坐标图 |
plt.boxplot(data, notch, position) | 绘制一个箱型图 |
plt.bar(left, height, width, bottom) | 绘制一个条形图 |
plt.barh(width,bottom,left,height) | 绘制一个横向条形图 |
plt.polar(theta,r) | 绘制极坐标图 |
plt.pie(data,explode) | 绘制饼图 |
plt.psd(x, NFFT = 256, pad_to, Fs | 绘制功率谱密度图 |
plt.cohere(x,y,NFFT=256,Fs) | 绘制X-Y的相关性函数 |
plt.specgram(x, NFFT=256,pad_to,F | 绘制谱图 |
plt.scatter(x,y) | 绘制散点图,其中,x和y长度相同 |
plt.step(x,y,where | 绘制步阶图 |
plt.hist(x,bins,normed) | 绘制直方图 |
plt.contour(X,Y,Z,N) | 绘制等值图 |
plt.vlines() | 绘制垂直图 |
plt.stem(x,y,linefmt,markerfmt) | 绘制柴火图 |
plt.plot_date() | 绘制数据日期 |
饼图的绘制
plt.pie()
import matplotlib.pyplot as plt
labels = "Frogs", "Hogs", "Dogs", "Logs"
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, autopct="%1.1f%%", shadow=False, startangle=90)
plt.savefig("testV12")
plt.show()
result:
直方图的绘制
plt.hist()
import matplotlib.pyplot as plt
labels = "Frogs", "Hogs", "Dogs", "Logs"
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, autopct="%1.1f%%", shadow=False, startangle=90)
plt.savefig("testV12")
plt.show()
极坐标绘制
plt.bar()
import numpy as np
import matplotlib.pyplot as plt
N = 20
theta = np.linspace(0.0, 2*np.pi, N, endpoint=False)
width = np.pi/4*np.random.rand(N)
radii = 10*np.random.rand(N)
ax = plt.subplot(111, projection="polar")
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r,bar in zip(radii, bars):
bar.set_facecolor(plt.cm.viridis(r/10.))
bar.set_alpha(0.5)
plt.savefig("testV14")
plt.show()
result:
Pandas库
Pandas库是Python第三方库,提供高性能易用数据类型和分析工具
引用: import pandas as pd
Pandas 基于Numpy实现,常与Numpy和Matplotlib一同使用
Simple test:
>>> import pandas as pd
>>> d = pd.Series(range(20))
>>> d
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
16 16
17 17
18 18
19 19
dtype: int64
左边代表索引,右边代表value
d.cumsum():计算前N项累加和
>>> d.cumsum()
0 0
1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55
11 66
12 78
13 91
14 105
15 120
16 136
17 153
18 171
19 190
dtype: int64
Pandas库的理解
两个数据类型: Series, DataFrame(一维,多维)
>>> import pandas as pd
>>> a = pd.Series([9, 8, 7, 6])
>>> a
0 9
1 8
2 7
3 6
dtype: int64
>>> import pandas as pd
>>> b = pd.Series([9, 8, 7, 6], index=['a', 'b', 'c', 'd']) # 自定义index
>>> b
a 9
b 8
c 7
d 6
dtype: int64
Series类型创建
1.从标量值创建
>>> import pandas as pd
>>> s = pd.Series(25, index = ['a', 'b', 'c'])
>>> s
a 25
b 25
c 25
dtype: int64
2.从字典类型创建
>>> s = pd.Series({'a':9, 'b':8, 'c':7}) # key 为index
>>> s
a 9
b 8
c 7
dtype: int64
>>> s = pd.Series({'a':9, 'b':8, 'c':7}, index = ['c', 'a', 'b', 'd'])
>>> s
c 7.0
a 9.0
b 8.0
d NaN
dtype: float64
3.从ndarray类型创建
>>> import pandas as pd
>>> import numpy as np
>>> n = pd.Series(np.arange(5))
>>> n
0 0
1 1
2 2
3 3
4 4
dtype: int32
>>> n = pd.Series(np.arange(5), index = np.arange(9, 4, -1))
>>> n
9 0
8 1
7 2
6 3
5 4
dtype: int32
Series的values和index
>>> import pandas as pd
>>> b = pd.Series([9, 8, 7, 6],['a', 'b', 'c', 'd'])
>>> b
a 9
b 8
c 7
d 6
dtype: int64
>>> b.index
Index(['a', 'b', 'c', 'd'], dtype='object')
>>> b.values
array([9, 8, 7, 6], dtype=int64)
DataFrame
DataFrame类型由共用相同索引的一组列组成
>>> import numpy as np
>>> import pandas as pd
>>> d = pd.DataFrame(np.arange(10).reshape(2,5))
>>> d
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
字典创建DataFrame
>>> import pandas as pd
>>> dt = {'one':pd.Series([1, 2, 3], index = ['a', 'b', 'c']),
'two':pd.Series([9, 8, 7, 6],index = ['a', 'b', 'c', 'd'])}
>>> d
0 1 2 3 4
0 0 1 2 3 4
1 5 6 7 8 9
>>> d = pd.DataFrame(dt)
>>> d
one two
a 1.0 9
b 2.0 8
c 3.0 7
d NaN 6
>>> pd.DataFrame(dt, index = ['b', 'c', 'd'], columns=['two', 'three'])
two three
b 8 NaN
c 7 NaN
d 6 NaN
列表类型的字典创建
>>> import pandas as pd
>>> d1 = {'one':[1, 2, 3, 4], 'two':[9, 8, 7, 6]}
>>> d = pd.DataFrame(d1, index = ['a', 'b', 'c', 'd'])
>>> d
one two
a 1 9
b 2 8
c 3 7
d 4 6
.reindex()重排
d = d.reindex(columns=[…]/index)