赞
踩
本文只为记录自己的学习,内容来自各位大佬,来源众多,故不挂了。若是需要的私信我,我来挂出大佬原文
Matplotlib 是专门用于开发2D图表(包括3D图表)的python库
对应的JS库有 D3 (opens new window)echarts
官网:Matplotlib
容器层
辅助显示层
图像层
2.0.1 最初图表
# 温度变化折线图
import matplotlib.pyplot as plt
import random
# 中文显示问题
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正确显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正确显示负号
# 1、准备数据
x=range(60)
y_shanghai=[random.uniform(15,18) for i in x]
y_beijing=[random.uniform(1,3) for i in x]
# random.uniform(x, y) 方法将随机生成一个实数,它在 [x,y) 范围内。
# 2、创建画布
plt.figure(figsize=(20,8), dpi=80) # 大小,像素点
plt.subplot(241)
plt.plot(x,y,"c.")
plt.title("青,点")
plt.subplot(242)
plt.plot(x,y,"r-.")
plt.title("红,点画")
plt.subplot(243)
plt.plot(x,y,'g--')
plt.title("绿,短划线")
plt.subplot(244)
plt.plot(x,y,'b-')
plt.title("蓝,实线")
plt.subplot(245)
plt.plot(x,y,'w.')
plt.title("白色,点")
plt.subplot(246)
plt.plot(x,y,"k-.")
plt.title("黑色,点画")
plt.subplot(247)
plt.plot(x,y,'y--')
plt.title("黄色,短划线")
plt.subplot(248)
plt.plot(x,y,'m-')
plt.title("洋红,实线")
plt.show()
2.0.2 修饰图表
import random
import matplotlib.pyplot as plt
# 中文问题
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正确显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正确显示负号
# 输入数据
x=range(60)
y=[random.uniform(15,18) for i in x]
# 绘制画布
plt.figure(figsize=(20,8),dpi=80)
# 绘制图像
#(0,0)
plt.subplot(241)
plt.plot(x,y,"c.",label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海未来温度一个小时的变化")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
#(0,1)
plt.subplot(242)
plt.plot(x,y,"r-.",label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海未来温度一个小时的变化")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
#(0,2)
plt.subplot(243)
plt.plot(x,y,'g--',label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海未来温度一个小时的变化")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
#(0,3)
plt.subplot(244)
plt.plot(x,y,'b-',label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海未来温度一个小时的变化")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
#(1,0)
plt.subplot(245)
plt.plot(x,y,'w.',label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海未来温度一个小时的变化")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
#(1,1)
plt.subplot(246)
plt.plot(x,y,"k-.",label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海未来温度一个小时的变化")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
#(1,2)
plt.subplot(247)
plt.plot(x,y,'y--',label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
#(1,3)
plt.subplot(248)
plt.plot(x,y,'m-',label='上海')
plt.legend()
plt.grid(linestyle='--',alpha=0.5) # 网格线透明度0.5
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海未来温度一个小时的变化")
x_label=[f"11点{i}分" for i in x]
plt.xticks(x[::10],x_label[::10])
plt.yticks(range(0,40,5))
plt.show()
以折线的上升或下降来表示统计数量的增减变化的统计图
特点:能够显示数据的变化趋势,反映事物的变化情况。(变化)
# 温度变化折线图
import matplotlib.pyplot as plt
import random
# 中文显示问题
plt.rcParams['font.sans-serif']=['SimHei'] # 用来正确显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正确显示负号
# 1、准备数据
x=range(60)
y_shanghai=[random.uniform(15,18) for i in x]
y_beijing=[random.uniform(1,3) for i in x]
# random.uniform(x, y) 方法将随机生成一个实数,它在 [x,y) 范围内。
# 2、创建画布
plt.figure(figsize=(20,8), dpi=80) # 大小,像素点
# 3、绘制图像
# plt.plot(x,y_shanghai,color='r',linestyle='-.',label='上海')
plt.plot(x,y_shanghai,'r-.',label='上海') # 简略题
plt.plot(x,y_beijing,'k.',label='北京')
# plt.show()
# 修饰图表
# 4、显示图例
plt.legend(loc=1) # loc=1右上角,loc=2左上角,loc=4右下角,loc=3左下角
# 5、显示网格
plt.grid(linestyle='-',alpha=0.5) # 网格透明度为0.5
# 6、添加描述、标题
plt.xlabel('时间')
plt.ylabel('温度')
plt.title('上海、北京温度变化')
# 7、修改x,y刻度
x_label=[f"11分{i}秒" for i in x]
plt.xticks(x[::5],x_label[::5])
plt.yticks(range(0,40,5))
plot.show()
用两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式。
特点:判断变量之间是否存在数量关联趋势,展示离群点(分布规律)
import matplotlib.pyplot as plt
import numpy as np
# 随机数种子
np.random.seed(50)
N=50
x=np.random.rand(N) # 生成50*1(1D)个0到1的数字
y=np.random.rand(N)
colors=np.random.rand(N)
area=(50*np.random.rand(N))**2
# 绘制画布
plt.figure(figsize=[20,8],dpi=80)
# 绘制图像
plt.scatter(x,y,s=area,c=colors,alpha=0.5) # 透明度
plt.show()
排列在工作表的列或行中的数据可以绘制到柱状图中。
特点:绘制连离散的数据,能够一眼看出名个数据的大小,比较数据之间的差别(统计/对比)
import matplotlib.pyplot as plt
# 1、准备数据
movie_names = ['雷神3:诸神黄昏','正义联盟','东方快车谋杀案','寻梦环游记','全球风暴', '降魔传','追捕','七十七天','密战','狂兽','其它']
tickets = [73853,57767,22354,15969,14839,8725,8716,8318,7916,6764,52222]
# 2、创建画布
plt.figure(figsize=(20,8),dpi=80)
# 3、绘制柱状图
colors=['b','r','g','y','c','m','y','k','c','g','b']
plt.bar(movies_names,tickets,color=colors)
plt.show()
由一系列高度不等的纵向条纹活线段表示数据分布的情况。
一般用横轴表示数据范围,纵轴表示分布情况。
特点:绘制连续性的数据展示一组或者多组的分布情况(统计)
直方图涉及统计学概念,首先要对数据分组,然后统计每组内数据元的数量。
在坐标系中,横轴标出每个组的端点,纵轴表示频数,每个矩形的高代表对应的频数,称这样子的统计图为频数分布直方图
# 需求:电影时长的分布情况
# 1、准备数据
time=[131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101,131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]
# 2、创建画布
plt.figure(figsize=(20,8),dpi=80)
# 3、绘制直方图
distance=2
group_num=int((max(time)-min(time))/distance)
plt.hist(time,bins=group_num,density=True)
用于表示不同分类的占比情况,通过弧度大小来对比各种分类。
特点:分类数据的占比情况(占比)
# 1、准备数据
movie_name = ['雷神3:诸神黄昏','正义联盟','东方快车谋杀案','寻梦环游记','全球风暴','降魔传','追捕','七十七天','密战','狂兽','其它']
place_count = [60605,54546,45819,28243,13270,9945,7679,6799,6101,4621,20105]
# 2、创建画布
plt.figure(figsize=(20, 8), dpi=80)
# 3、绘制饼图
plt.pie(place_count, labels=movie_name, colors=['b','r','g','y','c','m','y','k','c','g','y'], autopct="%1.2f%%")
# 显示图例
plt.legend()
plt.axis('equal')
# 4、显示图像
plt.show()
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
参数
有六个可选参数来控制子图布局。值均为0-1之间。其中left、bottom、right、top围成的区域就是子图的区域。wspace、hspace分别表示子图之间左右、上下的间距。实际的默认值由matplotlibrc文件控制的。
简单示例
# 0、load data
digits = load_digits()
# print("特征数据数组\n",digits.data)
# print("标签数组\n",digits.target)
# print("特征名\n",digits.feature_names)
# print("标签名\n",digits.target_names)
# 1、plot the digits
fig = plt.figure(figsize=(6, 6),dpi=80) # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
子图:就是在一张figure里面生成多张子图。
注意,pyplot的方式中plt.subplot()参数和面向对象中的add_subplot()参数和含义都相同。
# 法一
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax1.plot(x, x)
ax2 = fig.add_subplot(222)
ax2.plot(x, -x)
ax3 = fig.add_subplot(223)
ax3.plot(x, x ** 2)
ax4 = fig.add_subplot(224)
ax4.plot(x, np.log(x))
plt.show()
# 法二
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 100)
plt.subplot(221)
plt.plot(x, x)
plt.subplot(222)
plt.plot(x, -x)
plt.subplot(223)
plt.plot(x, x ** 2)
plt.subplot(224)
plt.plot(x, np.log(x))
plt.show()
inshow详解热图知识
热图是数据分析的常用方法,通过色差、亮度来展示数据的差异、易于理解。在matplotlib库中,调用imshow()函数来实现热图的绘制
imshow函数说明
imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
其中,x变量存储图像,可以是浮点数组、unit8数组以及PIL图像,如果其为数组,则需满足一下形状:
Colormap:参数camp用于设置热图的Colormap
Colormap是MATLAB里面用来设定和获取当前色图的函数,可以设置如下色图:
hot 从黑平滑过度到红、橙色和黄色的背景色,然后到白色。
cool 包含青绿色和品红色的阴影色。从青绿色平滑变化到品红色。
gray 返回线性灰度色图。
bone 具有较高的蓝色成分的灰度色图。该色图用于对灰度图添加电子的视图。
white 全白的单色色图。
spring 包含品红和黄的阴影颜色。
summer 包含绿和黄的阴影颜色。
autumn 从红色平滑变化到橙色,然后到黄色。
winter 包含蓝和绿的阴影色。
下面这段代码是显示原图、灰度(gray)、和春夏秋冬的示例。
import matplotlib.pyplot as plt
X = [[1, 2], [3, 4]]
fig = plt.figure()
ax = fig.add_subplot(231)
ax.imshow(X)
ax = fig.add_subplot(232)
im = ax.imshow(X, cmap=plt.cm.gray) #灰度
plt.colorbar(im, cax=None, ax=None, shrink=0.5)
ax = fig.add_subplot(233)
im = ax.imshow(X, cmap=plt.cm.spring) #春
plt.colorbar(im, cax=None, ax=None, shrink=0.5)
ax = fig.add_subplot(234)
im = ax.imshow(X, cmap=plt.cm.summer) #夏
plt.colorbar(im, cax=None, ax=None, shrink=0.5)
ax = fig.add_subplot(235)
im = ax.imshow(X, cmap=plt.cm.autumn)
plt.colorbar(im, shrink=0.5, ticks=[-1, 0, 1])
ax = fig.add_subplot(236)
im = ax.imshow(X, cmap=plt.cm.winter)
plt.colorbar(im, shrink=0.5)
plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。