Python--matplotlib(绘图库)基础学习

Matplotlib 入门级

 

Matplotlib :

  1. 最流行的Python底层绘图库,主要做数据可视化图表,模仿matlab构建.
  2. 能将数据进行可视化,更直观的呈现
  3. 使数据更加客观,更具说服力.
 1 # 基础绘图 示例
 2 #导入绘图库
 3 import matplotlib.pyplot as plt
 4 
 5 #构建坐标
 6 x = range(2,26,2) #取值2到26 每隔2位取1个值 包头不包尾
 7 y = [15,13,14.5,17,20,25,26,26,24,22,18,15]
 8 
 9 #画图  折线图
10 plt.plot(x,y)
11 
12 #显示图
13 plt.show()
View Code

Matplotlib基础功能表述 :

  设置图片大小及像素(分辨率,默认80)
#方法 figure(figsize=(宽,高),dpi=像素)
#示例
plt.figure(figsize=(20,10),dpi=100)
  保存图片
#方法 savefig('路径\文件名.文件类型') #jpg,sav,png
#示例
plt.savefig(r'C:\Users\luowe\Desktop\存图示例.jpg')
  X,Y轴刻度调整(传入x,y轴刻度数据)
#方法 xticks(x坐标) / yticks(y坐标)
#示例
plt.xticks(x)
plt.yticks(y)
   中文设置 : matplotlib默认不支持中文字符,需修改默认字体显示中文
#导库 
import matplotlib as mpl
mpl.rcParams['font.sans-serif']='字体'  #Kaiti,FangSong...
mpl.rcParams['font.size']=字体大小  #16,18,20...
  添加 '轴' 的描述信息
# 方法 xlabel('描述') / ylabel('描述')  #可选样式,属性  color颜色,fontdict字体设置,rotation旋转角度
#示例
plt.xlabel('Time',color='red' ,fontdict={'fontsize':30}) 
plt.ylabel('', color='blue',rotation=0)
  添加图 标题和网格
#方法 title('描述',样式设置) 标题,  grid(alpha=透明度)  网格 alpha选填 0~1
#示例
plt.title('某天10点到12点的气温变化表',color='green',fontdict={'fontsize':20})
plt.grid(alpha=0.5)
  图中多数据区分功能 
#如果一个图中有多条数据,可用 plt.plot(label='名称')和legend() 方法区分
#示例
plt.plot(x,me_y,label='me',color='red',linestyle='-.')
plt.plot(x,he_x,label='he',color='blue',linestyle='--')
plt.legend()
  图 点设置(最高点,最低点,自定义)
# 方法 annotate('名称,xy=(x,y),xytext=(x,y),color='颜色',arrowprops={'指示箭头样式':'箭头'})  #xy 标记点坐标  , xytext  文本名称显示的坐标位置, arrowprops 箭头样式 
#示例
plt.annotate('最高点',xy=(23,6),xytext=(25,6),color='blue',arrowprops={'arrowstyle':'<->','color':'turquoise'})
plt.annotate('最低点',xy=(12,0),xytext=(14,0),color='red',arrowprops={'arrowstyle':'<->','color':'purple'})

 

  示例 : 自定义绘图风格 and 颜色和线条选项(第二个代码框)

#导入随机功能库
import random as rd
#坐标
x = [rd.randint(1,30) for i in range(30)] #列表生成式 从1到30 随机取30个
y = [rd.randint(1,30) for i in range(30)]
#传参及样式设置
plt.plot(
    x,
    y,
    color='turquoise', # 线条颜色
    linestyle='--', #线条样式
    linewidth=5, #线条粗细
    alpha=0.5 #透明度
)
View Code
#颜色        #风格字符
r红色            - 实线
g绿色        -- 虚线
b蓝色            -. 点划线    
w白色    : 点虚线,虚线
c青色            '' 留空或者空格,无线条
m洋红
y黄色
k黑色
#0ff00 16进制
0.8灰度值字符串
View Code

  问题 : 列表a表示10点到12点每一分钟的气温, 如何绘制折线图观察每分钟气温的变化情况?

 1 #####完整代码展示#####
 2 
 3 #1. 导库
 4 import random as rd
 5 import matplotlib.pyplot as plt
 6 import matplotlib as mpl
 7 
 8 #2. 设置编码
 9 mpl.rcParams['font.sans-serif']='Kaiti'
10 mpl.rcParams['font.size']=18
11 
12 #3. 构建 x, y轴
13 x = list(range(120))
14 y = [rd.randint(20,36) for i in range(120)]
15 
16 #4. 设置图大小像素
17 plt.figure(figsize=(20,10),dpi=100)
18 
19 #5. 调刻度同上
20 xlable = ['10点{}分'.format(i) for i in range(60)]   
21 xlable += ['11点{}分'.format(i) for i in range(60)]  
22 
23 #6. 传参及数据调整(120条数据过多)丶切片
24 plt.plot(x,y)
25 plt.xticks(x[::3] , xlable[::3] ,rotation = 45) 
26 plt.yticks(y)
27 
28 #7. 添加x ,y 轴的描述
29 plt.xlabel('Time',color='red' ,fontdict={'fontsize':30}) #1号参数: 名称,2号参数:颜色,3号参数:样式{字体大小:X}
30 plt.ylabel('', color='blue',rotation=0)
31 
32 #8. 添加标
33 plt.title('某天10点到12点的气温变化表',color='green',fontdict={'fontsize':20})
34 #9. 添加网格
35 plt.grid(alpha=0.5)
36 plt.savefig(r'C:\Users\luowe\Desktop\存图示例3.jpg')
37 #10. 展示
38 plt.show()
View Code

  在一个图中画多个图 :

  问题:根据实际情况统计出来你和你的同桌各自从11岁到30岁每年交的女(男)朋友的数量如列表a和b,请在一个图中绘制出该数据的折线图,以便比较自己和同桌20年间的差异,同时分析每年交女(男)朋友的数量走势,给出如下数据

  a=[1,0,1,1,2,4,3,2,3.4,4,5,6,5,4,3,3,1,1.1]   b= [1,0,3,1,2,2,3,3,2,1,2,1,1.1,1,1,1,1,1.1]

#####完整数据展示#####
#1. 导库
import matplotlib.pyplot as plt
import matplotlib as mpl

#2. 设置字符编码
mpl.rcParams['font.sans-serif']='Kaiti'
mpl.rcParams['font.size']=20

#3. 构建图片大小
plt.figure(figsize=(20,8),dpi=100)

#4. 构建坐标
me_y = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1] #
he_y = [1,0,3,1,2,2,3,3,2,1,2,1,1,1,1,1,1,1,1,1] #同桌
x = range(11,31) #年龄11岁到30岁

#5. 设置刻度
all_year = ['{}岁'.format(i) for i in x]
plt.xticks(x,all_year)

#6. 传参
plt.plot(x,me_y,label='自己',color='red',linestyle='-.')
plt.plot(x,he_x,label='同桌',color='blue',linestyle='--')

#7. 网格
plt.grid(alpha=0.5)

#8. 我他识别
plt.legend()

#9. 设置x,y,,title  名称
plt.xlabel('年龄',color='gold',fontdict={'fontsize':25})
plt.ylabel('女朋友个数',color='green',fontdict={'fontsize':25})
plt.title('我和同桌11岁到30岁交往的女朋友个数比较',color='purple',fontdict={'fontsize':30})

#10. 最高点 最低点设置
plt.annotate('最高点',xy=(23,6),xytext=(25,6),color='blue',arrowprops={'arrowstyle':'<->','color':'turquoise'})
plt.annotate('最低点',xy=(12,0),xytext=(14,0),color='red',arrowprops={'arrowstyle':'<->','color':'purple'})
plt.savefig(r'C:\Users\luowe\Desktop\存图示例4.jpg')

#11. 展示
plt.show()
View Code
  点 (最高点,最低点,距离等箭头)
# text 想要标记的文本
# xytext 标记文本的坐标
# xy 被标记点的坐标 
# arrowprops 箭头形式
'''
=============================================
            Name           Attrs
            ============   =============================================
            ``'-'``        None
            ``'->'``       head_length=0.4,head_width=0.2
            ``'-['``       widthB=1.0,lengthB=0.2,angleB=None
            ``'|-|'``      widthA=1.0,widthB=1.0
            ``'-|>'``      head_length=0.4,head_width=0.2
            ``'<-'``       head_length=0.4,head_width=0.2
            ``'<->'``      head_length=0.4,head_width=0.2
            ``'<|-'``      head_length=0.4,head_width=0.2
            ``'<|-|>'``    head_length=0.4,head_width=0.2
            ``'fancy'``    head_length=0.4,head_width=0.4,tail_width=0.4
            ``'simple'``   head_length=0.5,head_width=0.5,tail_width=0.2
            ``'wedge'``    tail_width=0.3,shrink_factor=0.5
            ============   =============================================
'''
View Code

  基础小结(以上) :  

#1. 绘制了折线图plot(x,y)
#2. 设置图大小和分辨率率plt.figure(figsize=(?,?),dpi=?)
#3. 实现了图片的保存plt.savefig("?.?")
#4. 设置了XY轴上的刻度和字符串plt.xIy sticks(xly,替换值,rotation=?角度)
#5. 解决刻度稀疏和密集问题切片[x|y:?]
#6. 设置了title, x,y的label plt.title(),plt.xly label()
#7. 设置了字体mpl.rcParams["font.sans-serif],['font.size']
#8. 在- -个图上绘制多个图形plt.plot(x,y1) lplt.plot(x,y2)
#9. 为图形添加图例plt.legend(),需设置轴label=?
View Code

 

绘制散点图 scatter()

  散点图的应用场景

    不同条件(维度)之间的内在关联关系
    观测数据的离散程度

  假设通过爬虫你获取到了北京2016年3月份,10月份每天白天的最高气温(分别位于列表a, b),要求找出气温随时间变化的规律

 1 #####完整代码展示#####
 2 #1. 导库,设置字符编码,设图大小
 3 import matplotlib.pyplot as plt
 4 import matplotlib as mpl
 5 
 6 mpl.rcParams['font.sans-serif']='Kaiti'
 7 mpl.rcParams['font.size']=18
 8 
 9 plt.figure(figsize=(20,10),dpi=100)
10 
11 #2. 构建坐标 3和10 月份 各自的x,y轴 ,用于分开比较
12 y_3 = [10, 16, 17, 14, 12, 10, 12, 6, 6, 7, 8, 9, 12, 15, 15, 17, 18, 21, 16, 16, 20, 13, 15, 15, 15, 18, 20, 22, 22, 22, 24]
13 y_10 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20, 21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13, 12, 13, 6]
14 x_3 = list(range(1,32))
15 x_10 = [i+40 for i in x_3]  #10月份的轴向右移动了40位
16 
17 #3. 为散点图传入参数,并设置属性
18 plt.scatter(x_3,y_3,label='3月份温度',color='purple')
19 plt.scatter(x_10,y_10,label='10月份温度',color='blue')
20 
21 #4. 设置y轴刻度   温度
22 y=set(y_3+y_10) #温度集合到一起
23 max_y = max(y) #最高温度
24 min_y = min(y) #最低温度
25 
26 #5. 传入y刻度 最低温度到最高温度
27 plt.yticks(range(min_y,max_y+1))
28 
29 #6. 设置x轴刻度  日期
30 x = x_3+ x_10
31 x_lable = ['3月{}日'.format(i) for i in range(1,32)]+['10月{}日'.format(i) for i in range(1,32)]
32 
33 # ↓↓↓↓  x为上面3月份和10月份的日期总和
34 # ↓↓↓↓  x_lable为上面3月份和10月份的刻度替换值,rotation为旋转角度
35 plt.xticks(x[::3],x_lable[::3],rotation=45)
36 
37 #7. 显示最高温度,最低温度
38 plt.annotate('最高温度',xy=(43,28),xytext=(48,28),color='purple',arrowprops={'arrowstyle':'->'})
39 plt.annotate('最低温度',xy=(63,5),xytext=(52,5),color='red',arrowprops={'arrowstyle':'->'})
40 
41 #8. 标签设置及展示
42 plt.grid(alpha=0.5) #网格+透明度
43 plt.legend()  #显示区分标签 
44 plt.xlabel('月份', color='purple',fontdict={'fontsize':30})
45 plt.ylabel('温度',color='blue',fontdict={'fontsize':30},rotation=0)
46 plt.title('某年3月份和10月份温度比较散点图')
47 plt.show()
View Code

 

绘制条形图 [直向bar() 和 横向barh() ]

  条形图的应用场景

    数量统计    频率统计

  假设获取到2019年内地电影票房前20的电影(列表x)和电影票房数据(列表y),那么如何更加直观的展示数据。

  直-条形图 : 代码展示 : 

#1. 导库,编码,构图
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['font.sans-serif']='KaiTi'
mpl.rcParams['font.size']=18

plt.figure(figsize=(20,8),dpi=100)

#2. 构建坐标
movies = ['哪吒之魔童降世', '流浪地球', '复仇者联盟4:终局之战', '疯狂的外星人', '飞驰人生', '烈火英雄', '速度与激情:特别行动', '蜘蛛侠:英雄远征', '扫毒2天地对决', '大黄蜂', '惊奇队长', '比悲伤更悲伤的故事', '哥斯拉2:怪兽之王', '阿丽塔:战斗天使', '银河补习班', '狮子王', '反贪风暴4 ', '熊出没·原始时代', '使徒行者2:谍影行动', '大侦探皮卡丘']
y = [49.04, 46.18, 42.05, 21.83, 17.03, 16.74, 14.16, 14.01, 12.85, 11.38, 10.25, 9.46, 9.27, 8.88, 8.64, 8.23, 7.88, 7.09, 6.92, 6.34]
x = range(len(movies))

#3. 条形图 bar 
#传参 ,名称和数值
plt.bar(x ,y,width=0.5 ,color='orange')
plt.xticks(x,movies,rotation=-90,color='red')
#4. x,y,title 标签设置
plt.xlabel('电影名称',color='g',fontdict={'fontsize':30})
plt.ylabel('票房(亿元)',color='purple',fontdict={'fontsize':30})
plt.title('2019年内地前20名电影票房排行榜',color='blue',fontdict={'fontsize':45})
plt.show()
View Code

  横-条形图 : 代码展示 :

#横向方向
#1. 导库,编码,构图
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['font.sans-serif']='KaiTi'
mpl.rcParams['font.size']=18

plt.figure(figsize=(20,8),dpi=100)

#2. 构建坐标
movies = ['哪吒之魔童降世', '流浪地球', '复仇者联盟4:终局之战', '疯狂的外星人', '飞驰人生', '烈火英雄', '速度与激情:特别行动', '蜘蛛侠:英雄远征', '扫毒2天地对决', '大黄蜂', '惊奇队长', '比悲伤更悲伤的故事', '哥斯拉2:怪兽之王', '阿丽塔:战斗天使', '银河补习班', '狮子王', '反贪风暴4 ', '熊出没·原始时代', '使徒行者2:谍影行动', '大侦探皮卡丘']
y = [49.04, 46.18, 42.05, 21.83, 17.03, 16.74, 14.16, 14.01, 12.85, 11.38, 10.25, 9.46, 9.27, 8.88, 8.64, 8.23, 7.88, 7.09, 6.92, 6.34]
x = range(len(movies))

#3. 条形图 barh
#传参 ,名称和数值
plt.barh(x ,y,color='orange')
plt.yticks(x,movies,color='red')

#4. x,y,title 标签设置
plt.xlabel('票房(亿元)',color='g',fontdict={'fontsize':30})
plt.ylabel('电影名称',color='purple',fontdict={'fontsize':30})
plt.title('2019年内地前20名电影票房排行榜',color='blue',fontdict={'fontsize':45})
plt.show()
View Code

  问题 : 列表a中的电影的电影最近5天的电影分别在列表,b 25.b 26,b 27,b_ 28,b_ 29中,为了展示电影本身票房,及同其他电影数据的对比,应该如何更加直观的呈现数据。难点,注意细看

#0. 给予数据
a = ['决胜时刻', '诛仙Ⅰ', '小小的愿望']
b_25 = [891.4, 246.71, 550.45]
b_26 = [819.27, 397.18, 513.67]
b_27 = [867.78, 480.43, 752.36]
b_28 = [533.09, 500.42, 780.69]
b_29 = [679.87, 462.28, 374.11]

#1. 导库,字符编码,构图
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['font.sans-serif']='KaiTi'
mpl.rcParams['font.size']=18

plt.figure(figsize=(20,8),dpi=200)

#2. 5条数据比较用条形图
width = 0.1 #设置条形图宽度

#3. 传入数据,每插入一条数据x轴位移0.1个带你
plt.bar(range(3),b_25,width=width,label='最近1天')
plt.bar([i+1*0.1 for i in range(3)],b_26,width=width,label='最近2天')
plt.bar([i+1*0.2 for i in range(3)],b_27,width=width,label='最近3天')
plt.bar([i+1*0.3 for i in range(3)],b_28,width=width,label='最近4天')
plt.bar([i+1*0.4 for i in range(3)],b_29,width=width,label='最近5天')

#4. x 轴刻度调整;让电影名称在5天数据下方中间显示
plt.xticks([i+0.2 for i in range(3)],a)

#5. 标签设置
plt.legend()
plt.xlabel('电影名称',color='gold',fontdict={'fontsize':35})
plt.ylabel('票房(万元)',color='g',fontdict={'fontsize':35})
plt.title('2019年其3部电影近5日票房',color='red',fontdict={'fontsize':45})
plt.show()
View Code

绘制直方图  hist() 

  难度较大,细看品味

  问题 : 我们获取了347部电影的时长(列表data中)。希望统计出这些电影的时长的分布状态(比如时长100到120分钟电影的数量,出现频次)等信息,你该如何呈现这些数据?

#数据 电影时长
movies_time = [110, 201, 160, 152, 139, 178, 179, 83, 67, 132, 136, 177, 162, 110, 132, 115, 108, 102, 76, 105, 108, 24, 140, 162, 143, 165, 163, 95, 129, 137, 84, 93, 115, 96, 145, 173, 102, 116, 100, 120, 119, 88, 108, 136, 144, 111, 212, 87, 120, 91, 126, 55, 134, 181, 159, 138, 119, 138, 93, 155, 119, 88, 108, 136, 144, 111, 212, 87, 120, 91, 126, 55, 134, 181, 159, 138, 119, 138, 93, 155, 89, 140, 139, 75, 230, 179, 126, 178, 102, 91, 150, 96, 118, 100, 125, 130, 144, 140, 124, 157, 162, 121, 170, 111, 124, 99, 102, 75, 120, 139, 110, 138, 40, 70, 138, 137, 123, 133, 161, 83, 89, 140, 139, 75, 230, 179, 126, 178, 102, 91, 150, 96, 118, 100, 125, 130, 144, 140, 124, 157, 162, 121, 170, 111, 124, 99, 102, 75, 120, 139, 110, 138, 40, 70, 138, 137, 123, 133, 161, 83, 93, 121, 105, 106, 140, 101, 124, 148, 131, 101, 90, 90, 100, 129, 100, 94, 96, 89, 144, 100, 107, 90, 137, 133, 97, 84, 99, 142, 126, 132, 144, 124, 112, 111, 169, 151, 132, 169, 127, 120, 162, 121, 170, 111, 124, 99, 102, 75, 120, 139, 110, 138, 40, 70, 138, 137, 123, 133, 161, 83, 93, 121, 105, 106, 140, 101, 124, 148, 131, 101, 90, 90, 100, 129, 100, 94, 96, 89, 144, 100, 107, 90, 137, 133, 97, 84, 99, 142, 126, 132, 144, 124, 112, 111, 169, 151, 132, 169, 127, 120, 101, 141, 99, 139, 132, 93, 136, 127, 87, 96, 108, 120, 111, 130, 91, 237, 151, 76, 102, 64, 118, 84, 84, 105, 140, 144, 133, 93, 123, 147, 130, 149, 147, 121, 114, 105, 104, 98, 115, 93, 121, 105, 106, 140, 101, 124, 148, 131, 101, 90, 90, 100, 129, 100, 94, 96, 89, 144, 100, 107, 90, 137, 133, 97, 84, 99, 142, 126, 132, 144, 124, 112, 111, 169, 151, 132, 169, 127, 120, 101, 141, 99, 139, 132, 93, 136, 127]

#1.  导库,字符编码,构图
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['font.sans-serif']='KaiTi'
mpl.rcParams['font.size']=18

plt.figure(figsize=(20,10),dpi=100)

#2. 构建轴坐标
x = list(range(len(movies_time)))  #347部dy

#3. 最长时间和最低时间显示Y轴
max_time = max(movies_time)
min_time = min(movies_time)

#4. 测试组距
bins_width= 8 #暂时分8组
bins =(max_time-min_time)//bins_width  #// 取整
# print(type(bins))  int32

#5. 实际组距
real_width = (max_time-min_time)/bins  #组距离

#6. 设置X轴刻度
plt.xticks([min_time + i*real_width for i in range(bins)], rotation=45)

plt.hist(movies_time,bins)##???
plt.grid()
plt.show()
View Code

  需要注意的点 : 

1.组数的选择
    组数要适当,较少会有太大的统计误差,太多规律不明显。
    当数据在100个以内时,按数据多少-般分5-12组
    当数据较多时可以按照组距进行分组。
    组距:是指每组的两个端点的距离
    组数: =极差/组距= (最大数据最小数据) /组距
2. x轴刻度
    正常情况”下实际组距会是小数,所以刻度需要按照实际组距来,否则或出现图形偏移的情况
    实际组距=极差/组数
    刻度列表=[最小数据+实际组距*i for i in range(组数+ 1)]
3.频数直方图与频率直方图
    频率分布直方图纵轴表示频率/组距,横轴表示各组组距,若求某一组的频率, 就用纵轴的频率/组
    距*横轴的组距,即得该组频率。
    频率=频数/数据总数。

        

 

 

    问题 : 美国人口普查发现有1.24亿人在外工作.根据他们从家到上班弟弟昂所需要的时间,通过抽样统计出了下表这些数据,这些数据能绘制成直方图吗?

          

 

 

  思考这个数据能绘制直方图吗?
    给出的数据是统计之后的数据,所以为了达到直方图的效果,需要绘制条形图。
    结论:一般来说能够使用 plt.hist() 方法绘制直方图的是那些没有统计过的原始数据

 1 #1. 导库,字符编码,构图
 2 import matplotlib.pyplot as plt
 3 import matplotlib as mpl
 4 
 5 #2. 设置字符编码
 6 mpl.rcParams['font.sans-serif']='KaiTi'
 7 mpl.rcParams['font.size']=18
 8 
 9 #3. 设置图大小及分辨率
10 plt.figure(figsize=(20,10),dpi=100)
11 
12 #4.用条形图来模拟直方图
13 #数据
14 interval = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 60, 90, 150]   #间隔
15 width = [5, 5, 5, 5, 5, 5, 5, 5, 5, 15, 30, 60]   #宽度
16 quantity = [4180, 13687, 18618, 19634, 17981, 7190, 16369, 3212, 4122, 9200, 6461, 3435]   #数量
17 
18 #5.画图/绘图
19 for i in range(len(width)):
20     # 添加12次
21     plt.bar([interval[i]+width[i]/2],[quantity[i]],width=width[i],color='gold')
22     #         第一个间隔时间?+宽度的一半(图形偏移),数量,宽度=上面width的实际宽度
23     #1. 0+2.5,4180,5
24     #2. 5+2.5,13687,5
25     #3. 5+2.5,18618,5
26     #4......
27 plt.xticks(interval)
28 plt.grid()
29 plt.show()
View Code

 

  其他图形 : 

  matplotlib 还可以画其他图形,官网有详细案例,以及代码,在工作中如有需要,再进行查阅。
官网地址: https://matplotlib.org/gallery/index.html

posted @ 2019-10-21 23:31  逍遥大帝  阅读(1356)  评论(0编辑  收藏  举报