matplotlib基础
目录
pip install matplotlib==3.5.2 -i https://pypi.tuna.tsinghua.edu.cn/simple/
1.plt.plot()设置样式
-
配置格式
import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = [u'SimHei'] ##显示中文,设置字体 plt.rcParams['axes.unicode_minus'] = False ##显示符号 import warnings warnings.filterwarnings('ignore') # 忽略警告
-
设置坐标系的比例
plt.figure(figsize=(a,b))
#放在绘图的plot之前 #设置坐标系的比例plt.figure(figsize=(5,9)),横轴/纵轴=5/9 plt.figure(figsize=(5,9)) plt.plot(x,y)
-
设置图例
lenged()
plt.plot(x,y,label='x,y') plt.plot(x+1,y-2,label='x+1,y-2') plt.legend()
-
设置轴标识与标题
plt.plot(x,y) plt.xlabel('time') plt.ylabel('temp') plt.xticks(rotation=45) # x轴数据旋转45度 plt.title('time&temp',,size=25)
-
设置x轴刻度
fig = plt.figure(figsize=(10,9)) ax1 = fig.add_subplot(111) ax1.scatter(x, y,c='b',label='a') ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_xlim(50,0) # 50-0,而不是0-50
-
图例保存
#保存 fig=plt.figure()#该对象的创建一定要放置在plot绘图之前 plt.plot(x,y,label='x,y') fig.savefig('./data/123.png')
-
曲线的样式和风格
#设置颜色,透明度 plt.plot(x,y,c='red',alpha=0.5) #线型 plt.plot(x,y,ls='dashed') #点型 plt.plot(x,y,marker='8')
-
去除坐标轴数据
ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)
-
去除坐标轴边框
ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.spines['left'].set_visible(False)
-
同时去除坐标轴数据与边框
plt.axis('off')
-
保存图片去除空白
plt.savefig('data/a.jpg',bbox_inches = 'tight',pad_inches=-0.2,dpi=32) # pad_inches=-0.2 指自己调,还有空白,再设置小一点
-
设置不同刻度的y轴
import warnings import pandas as pd import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = [u'SimHei'] ##显示中文,设置字体 plt.rcParams['axes.unicode_minus'] = False ##显示符号 warnings.filterwarnings('ignore') # 忽略警告 fig,axes = plt.subplots(figsize=(10,9)) ax1=data.plot(x=x,y=y1,kind='scatter',c='b',marker='o',label='y1',ax=axes) ax1.legend(loc='upper left') ax2 = ax1.twinx() data.plot(x=x,y=y2,kind='scatter',c='g',label='y2',marker='^',ax=ax2) ax2.legend(loc='upper right') axes.set_title('title') axes.set_xlabel('xlabel') axes.set_ylabel('ylabel') fig.savefig('data/images/a.jpg')
2.绘制线性图:plt.plot()
- 绘制单条线形图
#绘制单条线形图 x=np.array([1,2,3,4,5]) y=x+3 plt.plot(x,y)
- 绘制多条线形图
#绘制多条线形图 #方式一 plt.plot(x,y) plt.plot(x+1,y-2) #方式二 plt.plot(x,y,x+1,y-2)
3.柱状图:plt.bar()
- 参数:第一个参数是索引,第二个参数是数据值,第三个参数是条形的宽度
- label:标签名
- label_type:标签类型,默认“edge",值显示在柱子的顶部
- rotation:标签值旋转45度
x=np.array([1,2,3,4,5]) y=x+3 plt.bar(x,y,width=10, label='flow_people', label_type='edge',rotation=45) for a,b,i in zip(x,y,range(len(x))): plt.text(x,y,y,ha='center',fontsize=20) # 直方图上方显示数据 (x,y,y)(x轴位置,y轴位置,要显示的数据)
4.直方图:plt.hist()
- 是一个特殊的柱状图,又叫做密度图
plt.hist()
的参数bins
:可以是一个bin
数量的整数值,也可以是表示bin
的一个序列,默认值为10normed
:如果值为True,直方图的值将进行归一化处理,形成概率密度,默认值为Falsecolor
:指定颜色,可以是单一颜色或颜色的序列。如果指定多个数据集合,例如:DataFrame
对象,颜色序列将会设置为相同的顺序,如果未指定,将默认使用默认的线条颜色orientation
:通过设置orientation
为horizontal
创建水平直方图,默认为vertical
data = [1,1,2,2,2,3,4,5,6,6,6,6,6,6,7,8,9,0] plt.hist(data,bins=20)
5.饼图:plt.pie()
- pie(),饼图只有一个参数x
- 饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小
- 参数
- labels:设置图例
- labeldistance:图例在图内圆心的0.3距离
- shadow:设置阴影
- autopct:精确小数点后6位
- explode:设置每块离圆心的距离
- pctdistance=0.9:autopct距离圆心的位置
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3,autopct='%.6f%%')
#不完整饼图
arr=[0.2,0.3,0.1]
plt.pie(arr)
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3,shadow=True,explode=[0.2,0.3,0.2,0.4])
6.散点图:plt.scatter()
- 简单图
- 因变量随自变量而变化的大致趋势
- 自变量的变化会导致因变量的变化
x=np.array([1,3,5,7,9]) y=x*2-3 plt.scatter(x,y)
- 多个y轴绘制图
import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = [u'SimHei'] ##显示中文,设置字体 plt.rcParams['axes.unicode_minus'] = False ##显示符号 fig,axes = plt.subplots(figsize=(10,9)) data.plot(x='x',y='y1',kind='scatter',c='b',marker='o',label='a',ax=axes) data.plot(x='x',y='y2',kind='scatter',c='g',label='b',marker='^',ax=axes) axes.set_title('correlation') axes.set_xlabel('x') axes.set_ylabel('y') fig.savefig('data/images/a.jpg')
- 3d图绘制
import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['font.sans-serif'] = [u'SimHei'] ##显示中文,设置字体 plt.rcParams['axes.unicode_minus'] = False ##显示符号 fig = plt.figure(figsize=(10,9)) ax = fig.add_subplot(111, projection='3d') ax.scatter(x,y,z,c='b',label='1') ax.scatter(x,y,z1,c='g',label='2') ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_title('title') # plt.show() plt.legend(labels=['1','2'], loc="upper right") fig.savefig('data/images/三维.jpg')
7.密度直方图
- 参数
- plt.figure(figsize=(16, 10)):设置图片的大小
- plt.xlim(,) :设置x轴值的范围
- plt.title():设置图的标题
fig = plt.figure(figsize=(16, 10))
plt.hist(data['flow_people'],density = True)
data['flow_people'].plot(kind = 'kde',c='blue')
plt.xlim(-1000,1000000)
plt.title('flow_people')
8.箱型图
fig = plt.figure(figsize=(10, 8))
plt.boxplot(box_data_flow_people,patch_artist=True, labels=['flow_people',"flow_people_top25"],widths=0.3)
plt.legend(['flow_people:\n0%:0\n 25%:3\n 50%:11\n 75%:51\n 100%:589627','flow_people_top25:\n0%:51\n25%:88\n50%:180\n75%:715\n100%:589627'],loc='upper center')
plt.savefig(fname="data/img/flow_people_box.png",figsize=[16,10])
plt.show()
9.绘制三维图
9.1. 三位散点图
import cv2
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
img=cv2.imread('./images/map2.jpg')
X=img.reshape(-1,3) # 宽(行),高(列),三个颜色点RGB
# 三维图
fig=plt.figure(figsize=(10,10))
ax=Axes3D(fig)
plt.scatter(X[:,0],X[:,1],X[:,2],alpha=0.1)
plt.show()
10.绘制多子图
10.1 柱状图
fig = plt.figure(figsize=(20, 25))
long=data_bar.shape[1]
for i in range(1,long-1):
# 2行2列 4个图片
plt.subplot(2, 2, i) # 子图的位置
date_index=0 if i<3 else 5
data_bar_new=data_bar.iloc[:,[date_index,i]]
date,name=data_bar_new.columns.to_list()
img_bar=plt.bar(data_bar_new[date],data_bar_new[name],width=10)
plt.bar_label(img_bar, label_type='edge',rotation=45)
plt.xticks(data_bar_new[date])
plt.xticks(rotation=45)
plt.xlabel(date,size=10)
plt.title(f'flow people {name}')
plt.savefig(fname="data/images/flow_people_bar.png")
plt.show()
10.2 箱型图和折线图
fig = plt.figure(figsize=(20, 10))
# 箱型图
plt.subplot(1, 2, 1)
sns.boxplot(x='x',y='y',data=data, showmeans=True,meanprops={"markeredgecolor": "green", "markersize": "10"})
plt.xlabel('x')
plt.ylabel('y')
# 折线图
plt.subplot(1, 2, 2)
plt.plot(data_mean[x],data_mean[y])
ax2=plt.xlabel('x')
ax2=plt.ylabel('y')
# 显示相关数值
for i in range(len(data_mean[x])):
ax2=plt.text(data_mean[x][i],data_mean[y][i],"{}".format(round(data_mean[y][i], 2) ),fontsize='10',color='green')
plt.show()
fig.savefig('data/a.jpg')
10.3 散点图与3d散点图
fig = plt.figure(figsize=(10,9))
# 2d散点图
ax1 = fig.add_subplot(221)
ax1.scatter(data[x], data[y],c='b',label='x')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
# 3d散点图
ax2 = fig.add_subplot(222, projection='3d')
ax2.scatter(data[x], data[y], data[z],c='b',label='误差距离/离摄像头的距离')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_zlabel('z')
ax2.set_title('scatter')
fig.savefig('data/a.jpg')