使用matploylib作图,记录也不详尽,之后如果用的多再进行补充。
官方文档:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.html
1. 变量关系
1.1 散点图
两变量关系,常用散点图
x=np.arange(50)
y=x+5*np.random.randn(50)
print('x:',x[0:10],'\n')
print('y:',y[0:10])
绘制散点图,直接使用x,y的数据即可:
plt.scatter(x,y)
plt.show()
1.2 气泡图
plt.scatter(x,y,s=x,c=y,alpha=0.5)
# s:气泡大小(可以设置其他数据)
# c:气泡颜色(可以设置其他数据)
# alpha:透明度
plt.show()
1.3 相关系数
多变量关系,可以计算相关系数矩阵,基于相关系数矩阵,展示热力图;还可以一个画布中多个子图,分别展示两两变量间关系。
1.3 相关系数矩阵
df_temp=pd.DataFrame({'A':[1,2,3,4,5,6,7],
'B':[3,3,5,7,8,2,1],
'C':[38,37,26,19,39,74,75],
'D':[12,46,85,67,39,27,93],
'F':[1,2,6,7,8,4,5]})
df_temp.corr()
1.2 相关系数热力图
使用seaborn包
seaborn官方文档:
https://seaborn.pydata.org/api.html
import seaborn as sns
plt.figure(figsize=(8,6))
sns.heatmap(df_temp.corr(),cmap="YlGnBu",annot=True)
#cmap:颜色
#annot:数据标签
1.3 两两关系展示
sns.pairplot(df_temp)
其他函数还有:PairGrid(可参见文档)
2. 统计量分布
2.1 柱形图
#生成柱形图数据
x=['A','B','C','D','E','F','G']
y1,y2=np.random.randint(1,25,size=(2,7)) #随机数
wid=0.25
print('x:',x,'\n',
'y1:',y1,'\n',
'y2:',y2)
2.1 普通柱形图、条形图
柱形图:
plt.bar(x=x,height=y1,width=0.5)
条形图:
plt.barh(y=x,width=y1,height=0.5)
2.2 簇状柱形图
p1=plt.bar(x,height=y1,width=0.25,
alpha=0.7,color='r',
label='一类') #设置类别
#第二个类别的图,是往右移了0.25(一个柱子的宽度)
p2=plt.bar([i+0.25 for i in range(0,7)],
height=y2,width=0.25,
alpha=0.7,color='g',
label='二类')
plt.xticks([i+0.1 for i in range(0,7)],x) #x轴刻度标签
plt.xlabel('类别')
plt.title('柱形图')
plt.legend() #设置题注(对应p1p2中的label)
#添加数据标签(挺繁琐)
for rect in p1:
height=rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2,
height+0.5,
str(height),ha='center',va='bottom')
for rect in p2:
height=rect.get_height()
plt.text(rect.get_x()+rect.get_width()/2,
height+0.5,
str(height),ha='center',va='bottom')
plt.show()
3. 数据分布图
3.1 直方图
import matplotlib.pyplot as plt
import numpy as np
data=np.random.randn(100)
data[0:20]
plt.hist(data,bins=10,
color='b',alpha=0.3)
plt.show()
(不得不说,做出来不好看。看数据特征可以,如果需要展示,需要调整细节或换其他工具)
3.2 箱线图
plt.boxplot(data)
4. 折线图
生成时序数据:
#生成日期
import pandas as pd
start_date='20200522'
gap=100
date_list1=pd.date_range(start=start_date,periods=gap).strftime('%Y%m%d').tolist()
print(date_list1[1:10])
print(len(date_list1))
输出:
[‘20200523’, ‘20200524’, ‘20200525’, ‘20200526’, ‘20200527’, ‘20200528’, ‘20200529’, ‘20200530’, ‘20200531’]
100
num1=np.random.randint(1,101,100) #生成1-101的随机整数
num2=np.random.randint(100,201,100)
df_temp=pd.DataFrame({'Time':date_list1,
'Number1':num1,
'Number2':num2})
df_temp.head()
4.1 单条折线图
df_temp.plot(x='Time',y='Number1')
plt.legend(['Number1'],loc='upper right')
4.2 多条折线图
plt.figure(figsize=(16,8))
plt.plot(df_temp['Time'],df_temp['Number1'],color='deeppink',
linewidth=2,linestyle=':',marker='o',label='Number1') #需要加label,不然图例不显示
plt.plot(df_temp['Time'],df_temp['Number2'],color='darkblue',
linewidth=1,linestyle='--',marker='+',label='Number2')
plt.xticks(rotation=45)
plt.xlabel(u'time',fontsize=14)
plt.tight_layout() #防止显示不全
plt.show()
但上述图形存在一个问题,就是横轴x轴的时间标签,虽然都显示出来了,但不清晰没有意义。
这时因为,df_temp这个数据框中的时间列Time是字符串格式,不是日期格式,转换为日期格式后,横轴时间标签不会全部显示,而是会自动以季度或月度数据显示。
字符串转换为日期格式:
df_temp['Time']=pd.to_datetime(df_temp['Time'])
然后作图如下:
常用作图设置:
plt.xticks(rotation=45) ---设置横轴x标签旋转45度,同样适用y轴
plt.xlabel('x轴') ---x轴坐标名字
plt.title('图形标题') ---图形标题设置
plt.rcParams['font.sans-serif']=['SimHei'] ---显示中文字体
plt.tight_layout() ---防止图形显示不全
plt.show() ---显示图形
5. 多个子图
首先加载包
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus']=False
子图设置需要的函数:
figure
- Matplotlib的图像均位于figure对象中
- 创建figure: fig=plt.figure()
%matplotlib inline
- 表示在jupyter notebook中显示图形
subplot
- fig.add_subplot(a,b,c)
- a,b表示将plot分割成a*b 的区域
- c表示当前选中要操作的区域
先设定位置作图-指定ax
比如要展示4张图,2行2列放置,那么要确定好位置。
#构造数据
random_arr=np.random.randn(100)
random_arr[0:20]
作图:
%matplotlib inline
fig=plt.figure()
#指定切分区域位置
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)
#默认是在最后一次使用subplot的位置上作图
plt.plot(random_arr)
#指定
'''
ax1.plot(random_arr)
ax2.plot(random_arr)
ax3.plot(random_arr)
'''
plt.show()
或者直接指定位置,不设置ax
但也会默认按照位置顺序排列
#另一表示方式
plt.subplot(2,2,1)
plt.plot(random_arr)
plt.subplot(2,2,2)
plt.plot(random_arr)
plt.subplot(2,2,3) #2行2列第3个图
plt.plot(random_arr)
6. 饼图
饼图,感觉用的比较少,做出来不加修饰也不太好看,但也是图形一部分,所以放在了最后面。
label_list=['第一部分','第二部分','第三部分'] #各部分标签
size=[55,35,10]
color=['red','green','blue']
explode=[0.005,0,0] #各部分突出
"""
绘制饼图
explode:设置各部分突出
label:设置各部分标签
labeldistance:设置标签文本距圆心位置,1.1表示1.1倍半径
autopct:设置圆里面文本
shadow:设置是否有阴影
startangle:起始角度,默认从0开始逆时针转
pctdistance:设置圆内文本距圆心距离
返回值
l_text:圆内部文本,matplotlib.text.Text object
p_text:圆外部文本
"""
#patches,l_text,p_text=
plt.pie(size,explode=explode,
colors=color,labels=label_list,
labeldistance=1.1,
autopct='%1.1f%%',
shadow=False,
startangle=90,pctdistance=0.6)
plt.axis('equal')
plt.legend()
plt.show()
(上面这个饼图的做法,还是先准备好比例数据,再进行作图的,比较繁琐,不如直接excel方便)
总结,在作图方面,个人觉得,数据量不多的情况,使用excel作图更方便,调整细节或颜色等很方便,而且保存清晰。
在python中使用工具包作图,是在数据量比较大的情况(用excel已经不好操作了),而且有时候作图不是为展示,而是在探索数据过程中,观察数据特征,更好地描述或分析数据。