第二部分—Numpy科学计算库基础
第一章–基本操作
第一节 数组创建
import numpy as np
arr = np.array([1,2,3,4,5])#生成一个array对象,这个对象是一维数组
np.ones(10) #10生成10个1的一维数组
np.zeros(10) #10生成10个0的一维数组
np.full(shape=[x,y],fill_value=10) #生成x行,y列的值全为10的数组
np.arrange(start= x, end = y, step = z) #从x 开始升序生成一个数组,到y结束(不包括y),步长为z
np.linspace(start= x, end = y, num = z) #从x 开始升序生成一个数组,到y结束(包括y),等差为z
np.random.randint(x, y, size = z) #从x到y随机生成长度为z的整数数组
np.random.random(x)
np.random.rand() #通过本函数可以返回一个或一组服从“0~1”均匀分布的随机样本值。随机样本取值范围是[0,1),不包括1。
#注:使用方法与np.random.randn()函数相同
np.random.randn(d0,d1,d2……dn)
1 当函数括号内没有参数时,则返回一个浮点数;
2 当函数括号内有一个参数时,则返回秩为1的数组,不能表示向量和矩阵;
3 当函数括号内有两个及以上参数时,则返回对应维度的数组,能表示向量或矩阵;
4 np.random.standard_normal()函数与np.random.randn()类似,但是np.random.standard_normal()
的输入参数为元组(tuple).
5 np.random.randn()的输入通常为整数,但是如果为浮点数,则会自动直接截断转换为整数。
第二节 查看操作
1.2.1 数组的轴数,维度
arr.ndim()
1.2.2数组的尺寸和形状
arr.shape # 形状
arr.size #大小尺寸
arr.dtype #数据类型 如int64
arr.itemsize
第三节 文件IO操作
1.3.1保存数组
x = np.random.randn(5)
y = np.random.randn(5)
np。save("xarr",x) #保存一个
np.save("arr.npz",xarr = x, yarr = y) #保存多个,存成文件
np.load("arr.npz")
np.load("arr.npz")["yarr"]
1.3.2读取csv,txt 文件
np.loadtxt("arr.txt",delimiter = ",", dtype = np.int32)
np.savetxt("arr.txt",delimiter = ",")
第二章-- 数据类型
ndarray的数据类型:
int: int8, uint8, int32 , int64
float: float16. float32, float64
str
2.1.1 array的创建和指定
np.array([1,2,3], dtype = "float32")
np.asarray([1,2,3], dtype = "float32") #与上面一样
2.1.2 数据类型转换 astype
arr.astype("float32")
第三章 数组运算
3.1.1 加减乘除幂
arr1 + arr2
arr1 - arr2
arr1 * arr2
arr1 / arr2
arr1 ** arr2 #幂
3.1.2 逻辑运算
arr1 > arr2arr1 < arr2arr1 >= arr2arr1 == arr2
3.1.3 数组与标量的运算
数组和标量的运算会将标量传到数组每一个值
arr1 + 5
3.1.4 *=,+=,-=
arr1 += arr2arr1 -= arr2arr1 *= arr2
第四章–复制和视图
4.1.1 完全没有复制
a = np.array([])b = ab is a #true a和b是不同变量名指向同一内存对象
4.1.2 查看或浅拷贝
不同的数组对象分享同一个数据。视图方法创造一个新的数组对象指向同一数据。
视图和源数据,数据用的同一内存,但是组织形式不同。
b = a.view()
4.1.3 深拷贝
b = a.clone()b.base is a #base 用于判断数组中的数据是否来自于别的数组
a.flags.owndata
b.flags.owndata
#flags.owndata 用于判断数组是否是数据的所有者
#ndarray.flags 返回 ndarray 对象的内存信息,包含以下属性:
属性描述
C_CONTIGUOUS (C)数据是在一个单一的C风格的连续段中
F_CONTIGUOUS (F)数据是在一个单一的Fortran风格的连续段中
OWNDATA (O)数组拥有它所使用的内存或从另一个对象中借用它
WRITEABLE (W)数据区域可以被写入,将该值设置为 False,则数据为只读ALIGNED (A)数据和所有元素都适当地对齐到硬件上
UPDATEIFCOPY (U)这个数组是其它数组的一个副本,当这个数组被释放时,原数组的内容将被更新
第五章–索引,切片和迭代
第一节 基本索引和切片
arr[:]arr[::2] #步长,每两个取一个/隔一个取一个
第二节 花式索引和所有技巧
arr1 = np.array([1,2,3,5,8,8,6,6,4,8,8])
arr2 = arr1[[1,5,2,6,5,5,2]]arr[::2] #步长,每两个取一个/隔一个取一个boolean 值索引
name = np.array(['A','b','c','e','e','f','g'])
c = name == 'A'
第六章–形状操作
第一节 数组变形
arr.reshape(4,3)arr.reshape(-1,3) #自动整形
第二节 数组转置
arr.Tnp.transpose(arr,axis = (2,0,1))
#后面的axes相当于转换维度,原本是(0,1,2)
第三节 数组迭代
np.concatenate(arr1,arr2, axis = 0) # 水平方向数组合并
np.concatenate(arr1,arr2, axis = 1) # 垂直方向数组合并
np.hstack(arr1,arr2) # 水平方向数组合并
np.vstack(arr1,arr2) # 垂直方向数组合并
第四节 数组拆分:split
np.split(arr, indices_or_sections = 2, axis = 0) # 按水平方向从第二行开始切分
np.split(arr, indices_or_sections = [2,3], axis = 1) # 按垂直方向从第二列到第二列(左开右闭)开始切分
np.hsplit(arr1, indices_or_sections = 2) # 水平方向数组合并
np.vsplit(arr1, indices_or_sections = [2,3]) # 垂直方向数组合并
第七章–广播机制
个人感觉广播就是矩阵相加减
第八章 --通用函数
np.sqrt(arr)
np.square(arr)
np.maximum(arr)
np.inner() #向量内积
where
个人感觉就是Java的三元表达式
cond = np.array([True, False, True, False, True])
np.where(cond, arr1, arr2)np.where(arr < 15, arr, 100)
排序
arr.sort()
np.sort(arr)
arr.argsort()#这个有点问题。。。
集合运算
np.intersectld(A, B) #取交集np.unionld(A, B) #取并集
np.setidffld(A, B) #取差集,取a中有,b没有
第九章–线性代数
矩阵乘积
np.dot(A, B)
矩阵其他计算
inv(A) --求逆矩阵det(A) --行列式
第十章 实战–用numpy分析鸢尾花各项特征
第三部分-- Pandas数据分析库
第一章 课程介绍
主要用于python 数据分析和建模部分
pandas是python的核心数据分析支持库
pandas主要数据结构是Series(一维数据)和DataFrame(二维数据)
处理数据主要分为几个阶段:
数据整理和清洗,数据分析与建模,数据可视化与制表
第二章 数据结构
第一节 Series
Series([data, index, dtype, name, copy, …])
l = [o,1,7,9,np.NaN , None , 1024,512] #这里l没什么用
s1 = pd.Series(data = 1)
s2 = pd.Series(data = 1, index = list("abcdefhi"),
dtype = "int32")
s3 = pd.Series(data = {"a":99 , "b":137 ,"c":149}
, name = "Python_score")
display(s1,s2,s3)
第二节 DataFrame
平均值,标准差,min,max,四分之几位数
df = pd.DataFrame(data = np.random.randint(0,151,size = (150,3)),
index ='None',#行索引默认
columns=['Python','Math', 'En'])#列索引
df.head( ) 前面
df.tail( ) 后面
df.shape #类型
df.dtypes
df.index
df.columns
df.describe
df.info()
第三章 csv
df = pd.DataFrame(data = np.random.randint(0,50,size = [50,5]),
columns = ['IT','化工','生物','教师','士兵'])
df.to_csv("./salary.csv",sep=";", header=True, index= True)
pd.read_csv("./salary.csv",sep=";",header=[0],index_col= 0)
pd.read_table("./salary.csv",sep=";",header=[0],index_col= 1)
第四章 Excel
df1 = pd.DataFrame(data = np.random.randint(0,50,size = [50,5]),
columns = ['IT','化工','生物','教师','士兵'])
df2 = pd.DataFrame(data = np.random.randint(0,50,size = [50,5]),
columns =['Python','TensorFlow','Keras'])
df2.to_excel("./ide.csv", header=True, index= False)
pd.read_excel("./salary.xls",sheet_name = 0,
header= 0, names = list('ABCDE'),index_col= 1)
pd.read_table("./salary.xls",sep=";",header=[0],index_col= 1)
#一个Excel文件中保存多个工作表
with pd.Excelwriter("./data.xlsx") as writer:
df1.to_excel(writer ,sheet_name="salary" , index = False)
df2.to_excel(writer ,sheet_name="ide" , index = False)
pd.read_excel("./data_excel_csv/data.xlsx",sheet_name= None)
#注意:当sheet_name = none时才输出一个文件中所有表
第五章 数据获取
第一节 标签选择
df = pd.DataFrame(data = np.random.randint(0,150,size = [10,3]),
index = list("ABCDEFGHIJ"),
columns=["Python", "Tensorflow", "Keras"])
df.loc[["A", "B", "c", "D", "F"]]
df.loc["A" : "E", ["Python", "Tensorflow"]]
df.loc[:, ["Keras", "Tensorflow"]]
df.loc["E"::2, ["python", "Tensorflow"]]
第二节 获取数据
df["python"]
df.Python
df[["Python", "Tensorflow"]]
df[3 : 15]
一开始以为,
以下三节都没讲,于是我找到了相应链接:https://www.cnblogs.com/ljhdo/p/14091198.html
.iloc 对应第三节
链接里的布尔索引对应第四节
第五节没有
请跳到06看以下三节
第三节 位置选择
#就是我找的iloc
df.iloc[4]
df.iloc[2:8, 0:2]
df.iloc[[1,3,5], [0,2,1]]
df.iloc[1:3, :]
df.iloc[:, :2]
df.iloc[0, 2]
第四节 Boolean索引
看我上面链接算了
第五节 赋值操作
果然是很简单的
df["PyTorch"] = s
df.loc["A", "Python"] = 256
df.iloc[3,2] = 512
第六章 数据集成
第一节 concat 数据串联
pd.concat([df1, df2], axis = 0)#感觉像数据库合并的操作
第二节 插入(更像是数据库的操作了)
pd.merge(df1, df2, how = axis = 0)#感觉像数据库合并的操作
pd.merge(left, right, how='inner',
on=None, left_on=None, right_on=None,
left_index=False, right_index=False,
sort=True,
suffixes=('_x', '_y'),
copy=True, indicator=False,
validate=None)
# 详细解释在下面链接# https://blog.youkuaiyun.com/brucewong0516/article/details/82707492
pd.round(n)方法返回 x 的小数点四舍五入到n个数字
⭐⭐第七章 数据清洗(重点)但还是讲的很差
#1、重复数据过滤
df.duplicated() #是对全部行进行查重,return (重复了) 的数据
df.drop_duplicates() #函数是将所有重复的数据都去掉了,且默认保留重复数据的第一条。
#具体解释看链接 https://blog.youkuaiyun.com/weixin_43852674/article/details/87717191
#2、空数据过滤
df.isnull # 可以用来判断缺失值
#详细:https://blog.youkuaiyun.com/qq_40825479/article/details/83544430df.dropna(how = "any") #主要用于滤除缺失数据。
df.fillna(value = x)
#填充 详细https://blog.youkuaiyun.com/weixin_39549734/article/details/81221276
#3、指定行和列过滤
del df["color"]df.drop(labels = ["xxx"],axis = 1)
#4、filter() 过滤
df.filter(items = ["xxx", "xxx"])
#5、异常值过滤视频就是将上面的几点组合做了个例子
第四部分-- Matplotlib 数据可视化
第一章 课程介绍
Matplotlib是一个Python的 2D给图库,它交互式环境生成出版质量级别的图形。通过 Matplotlib这个标准类库,开发者只需要几行代码就可以实现生成绘图,折线图、散点图、柱状图、饼图、直方图、组合图等数据分析可视化图表。
第二章 图像知识
第一节 图像绘图
import numpy as np
import matplotlib.pyplot as plt
#1。图形绘制
x = np.linspace(0, 2 * np.pi)
y = np.sin(x)
plt.figure()
plt.legend()#给图像加上图例。
plt.tick_params(axis='x',colors='white')
plt.tick_params(axis='y',colors='white') #设置坐标轴颜色
plt.xlim(-5,5) #轴范围
plt.ylim(-1,1)
plt.grid(linestyle = "--",color="green", alpha = 0.75)#网格线
plt.axis([a, b, c, d]) #设置x轴的范围为[a, b],y轴的范围为[c, d]
第二节 图例
import numpy as np
import matplotlib.pyplot as plt
#1。图形绘制
x = np.linspace(0, 2 * np.pi)
y = np.sin(x)
plt.figure()
#新知识点:设置坐标轴颜色
plt.tick_params(axis='x',colors='white')
plt.tick_params(axis='y',colors='white')
plt.xlim(-5,5) #轴范围
plt.ylim(-1,1)
plt.grid(linestyle = "--",color="green", alpha = 0.75)#网格线
plt.axis([a, b, c, d]) #设置x轴的范围为[a, b],y轴的范围为[c, d]
第三节 图片保存
import numpy as np
import matplotlib.pyplot as plt
#知识点
ax = plt.gca() #简单来说就是操纵坐标轴的
#gca()详解看链接 https://zhuanlan.zhihu.com/p/110976210
plt.savefig("./xxx.png",dpi = 100, facecolor = 'violet',
edgecolor= 'lightgreen')
🔺合并坐标轴
#合并数轴操作:
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))
ax.xaxis.set_ticks_position('top')
ax.spines['top'].set_position(('data',0))
ax.yaxis.set_ticks_position('right')
ax.spines['right'].set_position(('data',0))
第三章 风格和样式
第一节 颜色、线形、点形和透明度
#法一
plt.plot(x, y, '这里直接输入字符串即可表示颜色,线性,点形')
#法二,各自单独写
plt.plot(x, y, color='', ls='', market='')
#详解:
https://blog.csdn.net/weixin_43569478/article/details/107421677
https://zhuanlan.zhihu.com/p/258106097
第二节 更多属性设置
看上面链接即可
第四章–多图布局
第一节 子视图
plt.subplot(221) #两行两列图片为第一个位置
plt.sca(axex) #指定绘图区域
#figure就是一个图,axes表示图上的一个画图区域,
#一个图上可以有多个画图区域,意思就是说,一个图上可以有多个子图。
#用函数gcf()与gca()分别得到当前的figure与axes。
#(get current figure, get current axes).
#利用sca()函数实现把一个axes对象作为当前的axes,
#axes对象为figure对象的一个属性,
#当切换了axes,figure肯定也切换了。
第二节 嵌套
plt.axes([a,b,c,d])
#axes的用法和subplot是差不多的,四个参数的话,
#前两个指的是相对于坐标原点的位置,后两个指的是坐标轴的长/宽度
#详解:plt.axes()和plt.axis()区别 https://blog.youkuaiyun.com/u012413709/article/details/106503159
#感觉和上面差不多,没什么区别,也是子图
第三节 多图布局分格显示
fig,((ax11,ax12,ax13),(ax21,ax22,ax23),(ax31,ax32,ax33)) = plt.subplots(3,3) #视频写法,没见过fig.set_figwidth(9)
fig.set_figheight(6)
ax11.plot(x,np.sin(x))
ax12.plot(x,np.cos(x))
ax13.plot(x,np.tanh(x))
ax21.plot(x,np.tan(x))
ax22.plot(x,np.cosh(x))
ax23.plot(x,np.sinh(x))
ax31.plot(x,np.sin(x) +np.cos(x))
ax32.plot(x,np.sin(x * x) +np.cos(x * x))
ax33.plot(x,np.sin(x)*np.cos(x))
plt.tight_layout()plt.show( )
#我自己找了一个:
#https://www.cnblogs.com/coder-yy/p/14890446.html
#找到了" fig, ax = plt.subplots() "的资料,
#搜索关键词就是左边双引号内
https://www.cnblogs.com/komean/p/10670619.html
https://blog.csdn.net/htuhxf/article/details/82986440
第四节 不均匀分布
#法一
x = np.linspace(0, 2 * np.pi, 10)
fig = plt.figure(figsize = (12,9))
ax1 = plt.subplot(3,1,1)
ax1.plot(x,np.sin(10 * x))
ax1.set_title('ax1_title')
ax2 = plt.subplot(3, 3, (4, 5))
ax2.set_facecolor('green')
ax2.plot(x,np.cos(x), color = 'red')
ax3 = plt.subplot(3, 3, (6, 9))
ax3.plot(x, np.sin(x) + np.cos(x))
ax4 = plt.subplot(3,3,7)
ax4.plot( [1,3],[2,4])
ax5 = plt.subplot(3,3,8)
ax5.scatter([1,2,3],[0,2,4])
ax5.set_xlabel('ax5_x', fontsize = 12)
ax5.set_ylabel('ax5_y', fontsize = 12)
plt.show( )
#法二
x = np.linspace(0, 2 * np.pi, 10)
fig = plt.figure(figsize = (12,9))
#子图1
ax1 = plt.subplot2grid(shape = (3,3), #布局形状9个
colspan=3)#跨3列
ax1.plot(x, np.sin(10 * x))
ax1.set_title( 'ax1_title' )#设置ax1的标题、×lim ylim xlbale ylabl
#子图2
ax2 =plt.subplot2grid((3,3), (1, 0), colspan=2)
ax2.set_facecolor('green')
ax2.plot(x,np.cos(x) ,color = 'red' )
ax3 = plt.subplot2grid((3, 3),(1, 2), rowspan=2)
ax3.plot(x,np.sin(x) + np.cos(x))
#子图3
ax3 = plt.subplot2grid((3,3), (1, 2),rowspan=2)
ax3.plot(x,np.sin(x) + np.cos(x))
#子图4
ax4 = plt.subplot2grid((3,3),(2,0))
ax4.plot( [1,3],[2,4])
#子图5
ax5 = plt.subplot2grid( (3,3),(2,1))
ax5.scatter([1,2,3], [0,2,4])
ax5.set_xlabel('axs_x', fontsize = 12)
ax5.set_ylabel('ax5_y', fontsize = 12)
第五章 文本、注释和箭头
第一节 箭头
核心:
"""
x, y:箭头坐标
dx,dy:箭头x上的长度和y周的长度
length_includes_head: bool,箭头是否包含在长度之中,默认是false"""
plt.arrow(x,y,dx,dy,...)
例子:
#调入数据分析库
import matplotlib.pyplot as plt
import numpy as np
# 10行*2列
loc = np.random.randint(0,10,size = (10,2))plt.figure(figsize=( 10,10))
#输出图像,10行第1列,10行第2列
plt.plot(loc[: , 0], loc[:,1], "g*", ms = 20)
plt.grid(True)#路径: arange:等差数列,返回的0123456789
way = np.arange(10)
#shuffle(x)—{x :即将被打乱顺序的list ;返回主:‘}
np. random.shuffle(way)
#循环,返回的是索引
for i in range(0, len(way)-1):
start = loc[way[i]]
end = loc[way [i+1]]
plt.arrow(start[0],start[1],
end[0]-start[0], end[1]-start[1],
head_width=0.2,
lw=2,
length_includes_head = True)
plt.text(start[0],start[1],s = i,
fontsize = 18,
color = 'red')
#最后一个点
if i == len(way) - 2:
plt.text(end [0],end[1],s = i + 1,
fontsize = 18,
color = 'red')
#以上为视频代码, 箭头内容讲的很差
以下内容是我自己解释以及找的资料:https://blog.youkuaiyun.com/weixin_34080571/article/details/92302569
matplotlib.pyplot.arrow(
x, y,
dx, dy,
hold=None, **kwargs
)
#参数
x, y : 箭头起点坐标
dx, dy : 箭头x上的长度和y轴上的长度
width: 箭头宽度,默认0.001
length_includes_head: bool,箭"头"是否包含在长度之中 默认False
head_width: float,箭"头"的宽度,默认: 3*width
head_length: float 箭"头"的长度,默认1.5 * head_width
shape: [‘full’, ‘left’, ‘right’],箭头形状, 默认 ‘full’
overhang: float (default: 0)
head_starts_at_zero: bool (default: False)开始坐标是否是0
第二节 注释
核心:
"""
annotate()方法提供了辅助函数,使标注变得容易,
在标注中,
有2个要考虑的点,有
xy 的参数表示的标注位置 和 xytext 文本位置。
这2个参数都是(x,y) 元组
"""
ax.annotate(xy = , xytext = )
例子:
import matplotlib.pyplot as plt
# subplot ()返回的是2个对象,一个是初始化图,子图
fig, ax = plt.subplots()
#x轴数据
x = np.arange(0.0, 5.0, 0.01)
y = np.cos(2 * np.pi * x)
line = ax.plot(x, y, lw = 2)
ax.annotate(
"local max",#文本内容
xy=(2, 1), #箭头位置坐标(2,1)
xytext=(3, 1.5), #文本坐标位置(3,1.5)
arrowprops=dict(
facecolor="black", #black:箭头颜色为黑色
shrink=0.05) #shrink = 0.05
)
ax.annotate(
"local min",
xy=(2.5, -1),
xytext=(4, -1.8),
arrowprops=dict(
facecolor="black",
width=2,
headwidth=10,
headlength=10,
shrink=0.1)
)
ax.annotate(
"median",
xy=(2.25, 0),
xytext=(0.5, -1.3),
arrowprops=dict(arrowstyle="-|>"),
fontsize=20
)
ax.set_ylim(-2, 2)
第六章 常用视图
第一节 折线图
#视频例子
x = np.random.randint(0,10,size = 15)#取15个int类型的数据
plt.figure(figsize=(9,6)) #作图
plt.plot(x.cumsum() ,marker = 'o')
#多图布局:两个对象在不同图
fig,axs = plt.subplots(2,1)
fig.set_figwidth(9)
#多图布局: 两个对象在同一图
fig,axs = plt.subplots(2,1)
fig.set_figwidth(9)
fig.set_figheight(6)
axs[0].plot(x, marker = '*', color ='red')
axs [1].plot(x.cumsum() ,marker = 'o')
第二节 柱状图
2.1 堆叠柱状图
核心:
plt.bar( bottom = )
例子
labels=['G1','G2','G3','G4','G5','G6']
men_means = np.random.randint(20,35,size = 6)
women_means = np.random.randint(20,35,size = 6)
plt.bar(
labels,
men_means,
width,yerr = 4,
label = 'men')
plt.bar(
labels,
women_means,
width, #若不设置则自动设置宽度
yerr = 2,
bottom=men_means,
label = women')
plt.ylabel("Score")
plt.title("Score by group and gender")
plt.legend("upper right")
2.2 分组带标签柱状图
核心:
#核心代码在这个函数
def set_label(rects):
for rect in rects:
height = rect.get_height()#高度
plt.text(
x = rect.get_x( ) + rect.get_width()/2,# 水平坐标
y = height + 0.5, #竖直坐标
s = height, #文本
ha = 'center')#水平居中
例子
def set_label(rects):
for rect in rects:
height = rect.get_height()#高度
plt.text(
x = rect.get_x( ) + rect.get_width()/2,# 水平坐标
y = height + 0.5, #竖直坐标
s = height, #文本
ha = 'center')#水平居中
x = np.arange(len(men_means))
rects1 = plt.bar(x - width/2 , men_means ,width) #返回区域对象
rects2 = plt.bar(x + width/2 , women_means ,width)
plt.xticks(x,labels)plt.ylabel("Score")
plt.title("Score by group and gender")
plt.legend("Men","Women")
set_label(rects1)
set_label(rects2)
plt.tight_layout()
第三节 极坐标图
3.1 极坐标线型图
核心:
plt.subplot(projecttion = 'polar')
例子
r = np.arange(0,4 * np.pi, 0.01)#弧度值
y = np.linspace(0, 2, len(r)) #目标值
ax = plt.subplot(111, projection = 'polar' ,facecolor = 'lightgreen')#定义极坐标
ax.plot(r, y, color = 'red')
ax.set_rmax(3)#设置半径最大值
ax.set_rticks([0.5, 1, 1.5, 2])#设置半径刻度
ax.set_rlabel_position(-22.5)#设置半径刻度位置
ax.grid(True)#网格线
ax.set_title("A line plot on a polar axis",
va = 'center',
ha = 'center',pad = 30)
3.2 极坐标直方图
核心:
N = x
theta =
radius =
ax.bar(
theta,
radius,
width = width,
bottom = 0.0,
color = colors)
例子
#核心(用 !表示)
N=8 #分成8份!
theta = np.linspace(0, 2*np.pi, N, endpoint=False)
radius = np.random.randint(3, 15,size = N)
widht = np.pi / 4
colors = np.random.rand(8,3) #随机颜色
ax = plt.subplot(111 , projection = "polar") # polar表示极坐标!
ax.bar(theta , radius , width = width ,bottom = 0.0, color = colors)
第四节 直方图
核心:
plt.hist()
例子
mu = 100 #平均值
sigma = 15 #标准差
x = np.random.normal(loc = mu, scale = 15,size = 10000)
fig, ax = plt.subplots() #返回2个对象#hist:直方图
n,bins, patches = ax.hist(x, 200, density=True)
#正太分布公式
y = ((1 / (np.sqrt(2 * np.pi)* sigma))*np.exp(-0.5 * ( 1 / sigma * (bins - mu))**2))
plt.plot(bins, y, '--')
plt.xlabel('Smarts') #指定横轴的文本
plt.ylabel('Probability density')#指定纵轴的文本
plt.title(r'Histogram of IQ: $\mu=100$,$\sigma=15$')
fig.tight_layout( ) #紧凑输出
第五节 箱型图
核心:
plt.boxplot()
例子
data = np.random.normal(size=(500,4))
lables = ["A", "B", "c", "D"]
plt.boxplot(data,1,"gD",labels = lables)
第六节 散点图
核心:
plt.scatter()
例子
data = np.random.randn(100,2)
s = np. random.randint(100,300 ,size = 100)
color = np.random.randn(100)
plt.scatter(data[:,0], data[:,1], s = s, c = color ,alpha=0.3)
第七节 饼图
核心:
plt.pie()
例子:
import matplotlib as mpl #设置字符集,防止中文乱码
mpl.rcParams["font.sans-serif"] = [u'simHei'] #win自带的字体
#plt.rcParams [ 'font.sans-serif'] = ['Arial Unicode MS']#Mac自带的字体
mpl.rcParams["axes.unicode_minus"] = False
fig = plt.figure(figsize=(5, 5), dpi=100) #dpi∶像素点密度1008
p1 = [43, 25, 32]
p2 = [7, 22, 14, 5, 14, 6, 32]
labels = ['小狗','小猫', '小鸟']
def func(pct):
return '0.1f' % (pct) + '%'
plt.pie(p1,
autopct = lambda pct: func(pct),
radius=1,
pctdistance=0.85,
wedgeprops=dict(
linewidth=3,
width=0.4,
edgecolor='w'),
labels=labels)
plt.pie(p2,
autopct='%0.1f%%',
radius=0.7,
pctdistance=0.7,
wedgeprops=dict(
linewidth=3,
width=0.7,
edgecolor='w',
))
plt.legend(labels, loc='upper right',
bbox_to_anchor=(0.75, 0, 0.4, 1),
title='宠物占比')
⭐第八节 热力图
核心:
#目的:特征之间的相关系数,皮尔孙、cos ( )
plt.imshow()
例子:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
#ylabel()
vegetables = [ "cucumber","tomato", "lettuce" ,"asparagus" , "potato","wheat","barley"]
farmers = list( 'ABCDEFG')
harvest = np.random.rand(7,7)*5
plt.rcParams ['font.size' ] = 18
plt.rcParams ['font.weight' ] = 'heavy'
plt.figure(figsize=(9,9))
im = plt.imshow(harvest)
plt.xticks(
np.arange(len(farmers)),
farmers,rotation = 45,
ha = 'right')
plt.yticks(np.arange(len(vegetables)), vegetables)
for i in range(len(vegetables) ):
for j in range(len(farmers) ) :
text = plt.text(j, i, round( harvest[i,j],1),
ha = "center" , va="center" ,color='r')
plt.title("Harvest of local farmers (in tons/year)",pad = 20)
fig.tight_layout( )
plt.savefig('./热力图.png')
第九节 面积图
核心:
stackplot( ) #面积图
例子:
import matplotlib.pyplot as plt
plt.figure(figsize=(9,6))
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
plt.stackplot(days,sleeping,eating,working,playing)
plt.xlabel('x')#设置横轴文本的标记
plt.ylabel('y') #设置纵轴文本的标记
plt.title('Stack Plot',fontsize = 20)
plt.legend(['sleeping', 'Eating', 'working', ' Playing'],
fontsize = 18)