python数据分析 | Matplotlib全面介绍及使用

这篇博文主要是介绍Matplotlib模块的使用,具体包括用途介绍、安装、常用绘图以及配置操作。

1 Matplotlib 介绍及安装

(1)介绍:Matplotlib是一个Python的基础绘图库,它可与 NumPy 一起使用,代替Matlab使用。
(2)用途:绘图(将数据进行可视化,使数据更直观
使数据更加更具有说服力)
(3)安装 pip install matplotlib
安装可参考官网
https://matplotlib.org/users/installing.html

2 figure使用

介绍:Matplotlib所绘制的图位于图片(Figure)对象中,我们可以通过plt.figure生成一个新的图片

(1)语法
figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)

  • num:图像编号或名称,数字为编号 ,字符串为名称
  • figsize:指定figure的宽和高,单位为英寸
  • dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80
  • facecolor:背景颜色
  • edgecolor:边框颜色
  • frameon:是否显示边框
    (2)示例
    !注意: 在IPython/Pycharm中,执行该代码会有一个绘图窗口就会出现,但在Jupyter中则没有任何显示
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BKR83GYb-1597722086546)(attachment:image.png)]
    在这里插入图片描述

3 子图的绘制

3.1 subplot()

介绍:subplot可以规划figure划分为n个子图,但每条subplot命令只会创建一个子图
(1)语法
subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)

  • nrows :subplot的行数
  • ncols :subplot的列数
  • sharex :所有subplot应该使用相同的X轴刻度(调节xlim将会影响所有subplot)
  • sharey :所有subplot应该使用相同的Y轴刻度(调节ylim将会影响所有subplot)
  • subplot_ kw :用于创建各subplot的关键字字典
  • **fig_ kw :创建figure时的其他关键字,如plt.subplots(2,2,figsize=(8,6))
"""增加子图的的第一种使用:plt.subplot??"""
import numpy as np 
x = np.arange(0, 100)
#作图1
plt.subplot(221)   # 2*2:划分为2行2列,选择左上角的一个
plt.plot(x, x) 
#作图2
plt.subplot(222)  # 2*2:划分为2行2列,选择右上角的一个
plt.plot(x, -x)  
#作图3
plt.subplot(223)  # 2*2:划分为2行2列,选择左下角的一个
plt.plot(x, x ** 2)  
plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#作图4
plt.subplot(224)  # 2*2:划分为2行2列,选择右下角的一个
plt.plot(x, np.log(x))  
# 展示全图
plt.show()  

在这里插入图片描述

"""增加子图的第二种使用:plt.subplot??"""
import numpy as np 
x = np.arange(0, 100)
# 定义子图位置
ax1 = plt.subplot(2,2,1)   # 2*2 最多为4个图形 index=1 选择了第一个
ax2 = plt.subplot(2,2,2)
ax3 = plt.subplot(2,2,3)
ax4 = plt.subplot(2,2,4)
# 作图
ax1.plot(x,x) # 图 1
ax2.plot(x,-x) # 图 2
ax3.plot(x, x ** 2 ) # 图 3
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
ax4.plot(x, np.log(x)) # 图 4
# 展示全图
plt.show()  

3.2 plt.subplots()

介绍:Matplotlib包含一个便捷方法plt.subplots创建一个新的图片,然后返回包含了已生成子图对象的Numpy数组。
(1)语法
subplots参数与subplots相似

  • plt.subplots(nrows, ncols, sharex, sharey)
  • nrows子图的行数
  • ncols子图的列数
  • sharex 所有子图使用相同的x轴刻度
  • sharey 所有子图使用相同的y轴刻度
"""增加子图的第三种使用:plt.subplots??"""
import numpy as np 
x = np.arange(0, 100)
fig,axs = plt.subplots(2,2,sharex=False,sharey=False,figsize=(6,4)) # 2*2 nrows子图的行数 ncols子图列数 sharex,sharey 共享x,y轴
axs[0,0].plot(x,x) # 图 1
ax3s[0,1].plot(x,-x) # 图 2
axs[1,0].plot(x, x ** 2 ) # 图 3
axs[1,0].grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
axs[1,1].plot(x, np.log(x)) # 图 4

# 调整间距
plt.subplots_adjust(wspace=0,hspace=0)
plt.show()

3.3 add_subplots()和add_axes()

add_subplot与add_axes都是面对象figure编程的,pyplot api中没有此命令

3.3.1 add_subplot()新增子图

add_subplot的参数与subplots的相似
(1)语法
fig.add_subplot(nrows, ncols, index, **kwargs)

(2)示例

"""增加子图的第四种使用:fig.add_subplot??"""
import numpy as np  
import matplotlib.pyplot as plt  
x = np.arange(0, 100)  
#新建figure对象
fig=plt.figure()
#新建子图1
ax1=fig.add_subplot(2,2,1)      
ax1.plot(x, x) 
#新建子图2
ax2=fig.add_subplot(2,2,2)      
ax2.plot(x, -x) 
#新建子图3
ax3=fig.add_subplot(2,2,3)
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#新建子图4
ax4=fig.add_subplot(2,2,4)
ax4.plot(x, np.log(x))  
plt.show()

3.3.2 add_axes()新增子区域

介绍:add_axes为新增子区域,该区域可以座落在figure内任意位置,且该区域可任意设置大小
(1)语法
add_axes参数可参考官方文档:http://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure

(2)示例

import numpy as np  
import matplotlib.pyplot as plt  

#新建figure
fig = plt.figure()
# 定义数据
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
#新建区域ax1
#figure的百分比,从figure 10%的位置开始绘制, 宽高是figure的80%
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# 获得绘制的句柄
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_title('area1')

#新增区域ax2,嵌套在ax1内
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
# 获得绘制的句柄
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(x,y, 'b')
ax2.set_title('area2')
plt.show() 

在这里插入图片描述
参考:【Python】 【绘图】plt.figure()的使用

4 Matplotlib绘制图形

matplotlib能够绘制折线图,散点图,条形图,直方图,饼图等等.
具体可以参考学习网址:https://matplotlib.org/gallery/index.html
网址给了很好的示例,入门看这个完全ok
还可以看这个,有详细的语法:
绘图参考链接: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.html#module-matplotlib.pyplot
首先,先来了解一下图形的构成
在这里插入图片描述
实现方法如下,绘图常用:

  • plt.figure(figsize=None,dpi=None):生成新的图片,figsize:图片大小,dpi:透明度
  • plt.savefig(fname) :保存图片
  • plt.xticks(ticks=None) : 设置x轴刻度的值
  • plt.yticks(ticks=None) :设置y轴刻度的值
  • plt.xlabel(xlabel) : 设置x轴标签
  • plt.ylabel(ylabel) : 设置y轴标签
  • plt.title():设置图标题
  • plt.grid() : 根据x轴和y轴的数值展示轴网格

4.1 绘制图形的中文显示问题

当我们需要设置轴标签,标题等,通常会使用到中文。但是,matplotlib默认不显示中文。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IqIpPMiO-1597722497323)(attachment:image.png)]
解决方法有三种

# 设置matplotlib自带的字体 只能设置.ttf字体,不支持.ttc字体
# """
# 方法1:全局的设置方式
# """
# import matplotlib
# font = {
#     'family':'SimHei',
#     'weight':'bold',
#     'size':12
# }
# matplotlib.rc("font", **font)
# # matplotlib.rc??
# """
# 方法2:全局的设置方式
# """
# import matplotlib.pyplot as plt
# plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
# plt.rcParams['axes.unicode_minus'] = False   # 步骤二(解决坐标轴负数的负号显示问题)
"""
方法法3:局部的设置方式
相当于将字体注册到了matplotlib字体库中
"""
from matplotlib.font_manager import FontProperties 
font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14)

4.2 折线图

(1)介绍:折线图以折线的上升或下降来表示统计数量的增减变化的统计图
(2)特点:能够显示数据的变化趋势,反映事物的变化情况
(3)绘制

  • plt.plot(x, y) # 使用默认的线样式及颜色绘制x,y构建的图形
    (4)语法
    plot(x, y, color=‘green’, marker=‘o’, linestyle=‘dashed’, linewidth=2, markersize=12)
  • color : 颜色设置
  • marker : 数据点标签
  • linestyle : 线的设置
  • linwidth : 线宽
  • markersize : 数据点标签
  • plt.plot?? : 其他参数见help

(5)示例

"""
示例:假设一天中每隔两个小时的气温分别是[15,13,14.5,17,20,25,26,26,27,22,18,15],绘制图形变化:折线 x:时间 y:温度
"""
# 放大画布
plt.figure(figsize=(8,6))

# 每隔两个小时  2 4 6 8... 24
x = range(0,24,2)
y = [15,13,14.5,17,20,25,26,26,27,22,18,15]

# 设置x刻度和标签
x_t = [i/2 for i in range(0,48)]
x_l = ["{}点".format(i/2) for i in range(0,48)]
plt.xticks(x_t[::4],x_l[::4],rotation=45,fontproperties=font)   # x_t刻度,x_l刻度标签  间隔4h([::4]) 设置中文字体

# 设置y刻度 最大值最小值
y_t = range(min(y),max(y)+1)
plt.yticks(y_t)

# 添加x轴标签
plt.xlabel("time")

# 添加y轴标签
plt.ylabel("temperature")

# 添加标题
plt.title("temperature change")

# 添加网格
plt.grid()

# 绘制图形
plt.plot(x,y)

# 保存图片 注意:要在show之前保存 否则:空白图 
plt.savefig("mat.jpg")

# 展示图形 释放
plt.show()

4.3 散点图

(1)介绍:散点图用两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种关联或总结坐标点的分布模式
(2)特点:判断变量之间是否存在数量关联趋势,表示离群点(分布规律)
(3)语法:plt.scatter(x,y) # 以默认的形状颜色等绘制散点图
(4)示例

"""
假设通过爬虫你获取到了长沙2019年4,10月份每天白天的最高气温(分别位于列表a,b),那么此时如何寻找出气温和随时间变化的某种规律
- a = [11,17,16,11,12,11,12,13,10,14,8,13,12,15,14,17,18,21,16,17,30,14,15,15,15,19,21,22,22,22,23]
- b = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,15,10,11,13,12,13,6]
"""
# plt.scatter??
# 优化:4,10月份的分布分开
# x,y
y_4 = [11,17,16,11,12,11,12,13,10,14,8,13,12,15,14,17,18,21,16,17,30,14,15,15,15,19,21,22,22,22,23]
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,15,10,11,13,12,13,6]
x_4 = range(1,32)    # 1~31
x_10 = range(51,82)  # 20+31 ~ 31+31+20

# 绘制图形
plt.scatter(x_4,y_4)
plt.scatter(x_10,y_10)

# 刻度 四月1号 四月31号   十月1号..十月31号
x_t = list(x_4)+list(x_10)
x_l = ["四月{}号".format(i) for i in x_4]
x_l += ["十月{}号".format(i-50) for i in x_10]  # 51-50,81-50
plt.xticks(x_t[::4],x_l[::4],fontproperties=font,rotation=45)

plt.show()

在这里插入图片描述

4.4 条形图

(1)介绍:条形图是用宽度相同的条形的高度或长短来表示数据多少的图形。条形图可以横置或纵置,纵置时也称为柱形图。
(2)特点:

  • 能够使人们一眼看出各个数据的大小
  • 易于比较数据之间的差别
    (3)语法:
  • 竖向条形图: plt.bar(x, height) # 绘制以x为x轴位置,height为y轴位置的竖条形图
  • 水平条形图:plt.barh(y, width) # 绘制以y为y轴位置,width为y轴位置的水平条形图

4.4.1 简单条形图

# 简单条形图
# 构建x,height
a = ["流浪地球","复仇者联盟4:终局之战","哪吒之魔童降世","疯狂的外星人","飞驰人生","蜘蛛侠:英雄远征","扫毒2天地对决","烈火英雄","大黄蜂","惊奇队长","比悲伤更悲伤的故事","哥斯拉2:怪兽之王","阿丽塔:战斗天使","银河补习班","狮子王","反贪风暴4","熊出没","大侦探皮卡丘","新喜剧之王","使徒行者2:谍影行动","千与千寻"]
b = [56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23,5.22]

# 放大画布
plt.figure(figsize=(14,8))

# 柱状图
# width 调整柱子的宽度 默认0.8
# bottom  y的起始值改变了  堆叠图
# align 默认为:center居中  设置为:edge边缘 取决于width的正负  正:右边 负:左边
plt.bar(a,b,width=-0.3,bottom=10,align="edge")

# 设置刻度
plt.xticks(fontproperties=font,rotation=90)

plt.show()

4.4.2 分组条形图

# 分组条形图
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif'] = ['SimHei'] # 步骤一(替换sans-serif字体)
plt.rcParams['axes.unicode_minus'] = False   # 步骤二(解决坐标轴负数的负号显示问题)

# 创建x轴、y轴
fruits = ["苹果","梨子","车厘子"]
Q1_sales = [1000,800,3000]
Q2_sales = [1200,700,2800]
x = np.arange(len(fruits))  # the label locations
width = 0.35  # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, Q1_sales, width, label='Q1_sales')
rects2 = ax.bar(x + width/2, Q2_sales, width, label='Q2_sales')

# 添加标签、标题等
ax.set_ylabel('销售量')
ax.set_title('上半年水果销量')
ax.set_xticks(x)
ax.set_xticklabels(fruits)
ax.legend()
def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)

# 调整布局
fig.tight_layout()

# 展示图形
plt.show()

在这里插入图片描述

4.4.3 堆叠条形图

# 构建x,height
fruits = ["苹果","梨子","车厘子"]
Q1_sales = [1000,800,3000]
Q2_sales = [1800,200,2800]

plt.bar(fruits,Q1_sales,width=0.5,label="Q1")
plt.bar(fruits,Q2_sales,width=0.5,bottom=Q1_sales,label="Q2")

plt.legend()
plt.show()

在这里插入图片描述

4.4.4 水平条形图

a = ["流浪地球","复仇者联盟4:终局之战","哪吒之魔童降世","疯狂的外星人","飞驰人生","蜘蛛侠:英雄远征","扫毒2天地对决","烈火英雄","大黄蜂","惊奇队长","比悲伤更悲伤的故事","哥斯拉2:怪兽之王","阿丽塔:战斗天使","银河补习班","狮子王","反贪风暴4","熊出没","大侦探皮卡丘","新喜剧之王","使徒行者2:谍影行动","千与千寻"]
b = [56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23,5.22]

plt.figure(figsize=(14,8))
plt.barh(a,b,height=0.5)

plt.show()

4.5 直方图

(1)介绍:直方图由一系列高度不等的纵向条纹或线段表示数据分布的情况,一般用横轴表示数据范围,纵轴表示分布情况
(2)特点:绘制连续性的数据,展示一组或者多组数据的分布情况(统计)
(3)语法:plt.hist(x, bins=None) # 绘制以x为数值,bins为组数 (组数 = 极差/组距)

"""
示例:某地区连续50年中四月份平均气温数据如下: temp_li= [6.9,4.1,6.6,5.2,6.4,7.9,8.6,3.0,4.4,6.7,7.1,4.7,9.1,6.8,8.6,5.2,5.8,7.9,5.6,8.8,8.1,5.7,8.4,4.1,6.4,6.2,5.2,6.8,5.6,5.6,6.8,8.2,6.4,4.8,6.9,7.1,9.7,6.4,7.3,6.8,7.1,4.8,5.8,6.5,5.9,7.3,5.5,7.4,6.2,7.7] 根据以上数据,推断该地区四月份平均气温的分布类型。
"""
temp_li= [6.9,4.1,6.6,5.2,6.4,7.9,8.6,3.0,4.4,6.7,7.1,4.7,9.1,6.8,8.6,5.2,5.8,7.9,5.6,8.8,8.1,5.7,8.4,4.1,6.4,6.2,5.2,6.8,5.6,5.6,6.8,8.2,6.4,4.8,6.9,7.1,9.7,6.4,7.3,6.8,7.1,4.8,5.8,6.5,5.9,7.3,5.5,7.4,6.2,7.7]

# 求 bins 组数  组数=极差/组距
max(temp_li)   # 9.7
min(temp_li)   # 3.0   
cha = max(temp_li) - min(temp_li)  
b = 1
bi = round(cha)//b     # 去差一下 python当中的四舍五入 
 
plt.hist(temp_li,bins=bi,density=True)  # 注意:bins 一定是整数类型 默认为10

# 显示标签
plt.xlabel("区间")
plt.ylabel("频数/频率")
plt.title("直方图")

plt.show()

在这里插入图片描述

4.6 扇形图

(1)介绍:扇形图,用整个圆表示总数,用圆内各个扇形的大小表示各部分数量占总数的百分数。
(2)语法:通过pie()函数绘制
plt.pie(x, explode=None, labels=None)

  • x :扇形数据
  • explode:设置某几个分块是否要分离饼图
  • labels:每块扇形标签
  • autopct:百分比数据标签
  • shadow :是否显示阴影
    plt.pie()有3个返回值
  • patches 绘制饼图每一块的对象
  • texts 文本的列表
  • autotexts 百分比的文本列表
# plt.pie??

frac = [1/50,6/50,11/50,15/50,9/50,6/50,2/50]
label = ['[3,4]','(4,5]','(5,6]','(6,7]','(7,8]','(8,9]','(9,10]']
explodes = (0,0,0.1,0,0,0,0) # 设置某几个分块是否要分离饼图
patches,texts,autotexts = plt.pie(frac,labels=label,autopct="%.2f%%",explode=explodes,shadow=True,textprops={"size":15})
# print(patches)  # patches 绘制饼图每一块的对象
# print(texts)   # texts 文本的列表
# print(autotexts)  # autotexts 百分比的文本列表

# 设置百分比数值 字体为白色
for autotext in autotexts:
    autotext.set_color("w")

plt.show()

在这里插入图片描述

4.7 箱型图

(1)介绍:一种直观简洁的方式去呈现一组数据的分布。 箱线图广泛用于各个数据分析领域,它能非常简单明了地显示一组数据中5个重要数值,并且还能发现一组数据中的存在的异常值。(最大值 、最小值、中位数、下四分位数(Q1)、上四分位数(Q3))
(2)语法:plt.boxplot()

  • x:需要绘制的箱型图的数据
  • notch:是否展示置信区间 默认为False
  • sym:代表异常点的符号表示 默认为圆点
  • vert:是否是垂直的 默认是True
  • whis:上下限系数 默认为1.5
  • positions:设置每个盒子的位置
  • widths:设置每个盒子的宽度
  • labels:每个盒子的label
  • meanline和showmean:都为True的时候 会展示平均线
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fsq5vgsw-1597722987428)(attachment:image.png)]
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

data = np.random.randint(1,100,size=100)
data = np.append(data,np.array([-100,300]))   # 添加两个异常值
plt.boxplot(data,sym="^",widths=0.2,meanline=True,showmeans=True)
plt.show()

在这里插入图片描述

4.8 雷达图

(1)介绍:雷达图(Radar Chart)又被叫做蜘蛛网图,适用于显示三个或更多的维度的变量的强弱情况。比如某个企业在哪些业务方面的投入等,都可以用雷达图方便的表示。
(2)语法:在matplotlib.pyplot中,可以通过plt.polar来绘制雷达图,这个方法的参数跟plt.plot非常的类似,只不过是x轴的坐标点应该为弧度(2*PI=360°)。

import numpy as np

quaters = ['Q1','Q2','Q3','Q4']   
sales = [40,91,44,90,40] #  再添加第一个值 40 ,使线条闭合
theta = np.linspace(0,np.pi*2,5) 
plt.polar(theta,sales)         
# plt.xticks(theta,quaters,fontproperties=font)
plt.fill(theta,sales)      

在这里插入图片描述

5 Matplotlib配置

5.1 Axes容器

(1)介绍:Axes容器是用来创建具体的图形的。比如画曲线,柱状图,都是画在上面。所以之前我们学的使用plt.xx绘制各种图形(比如条形图,直方图,散点图等)都是对Axes的封装。
学习参考:https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes
(2)使用1 : 设置x和y轴的最大值与最小值
设置完刻度后,我们还可以设置x轴和y轴的最大值和最小值。可以通过set_xlim/set_ylim来实现:

from matplotlib import pyplot as plt

fig = plt.figure()
ax1 = plt.subplot(111)
ax1.plot(range(10),range(10))
ax1.set_xlim(-2,12)      
ax1.set_xticks(range(10)) 

plt.show()

(3)使用2:添加文本
之前添加文本我们用的是annotate,但是如果不是需要做注释,其实还有另外一种更加简单的方式,那就是使用text方法:

fig = plt.figure()
ax1 = plt.subplot(111)
ax1.plot(range(10),range(10),marker="o")

# 想在(0,0)的位置显示文本
ax1.text(0-0.2,0+0.5,"(0,0)")

plt.show()

(3) 使用3:绘制双y轴

  • 绘制图1为: ax1
  • 通过 ax2 = ax1.twinx() 克隆 ax1
  • 绘制图2位: ax2
import random
fig = plt.figure()

# 绘制ax1
ax1 = plt.subplot(111)
ax1.bar(range(10),[random.randint(-10,40) for i in range(10)])
ax1.set_ylabel("温度")

# 克隆ax1 共享x轴
ax2 = ax1.twinx()
ax2.plot(range(10),[random.randint(0,100) for i in range(10)],marker="o",color="r")
ax2.set_ylabel("降水量")

plt.show()

在这里插入图片描述

5.2 Axis容器

(1)介绍:Axis代表的是x轴或者y轴的对象。包含Tick(刻度)对象,TickLabel刻度文本对象,以及AxisLabel坐标轴文本对象。axis对象有一些方法可以操作刻度和文本等
学习参考:https://matplotlib.org/api/axis_api.html#matplotlib.axis.Axis
(2)使用1:设置x轴和y轴label的位置

  • ax1.yaxis.set_label_coords(x,y)
fig = plt.figure()

# 绘制ax1
ax1 = plt.subplot(111)
ax1.bar(range(10),[random.randint(-10,40) for i in range(10)])
ax1.set_ylabel("温度")

# 设置y轴label的位置为上方
ax1.yaxis.set_label_coords(-0.1,1)

(3)使用2:设置刻度上的刻度格式

from matplotlib import ticker

fig = plt.figure()

# 绘制ax1
ax1 = plt.subplot(111)
ax1.bar(range(10),[random.randint(-10,40) for i in range(10)])
ax1.set_ylabel("温度")

# 自定义刻度格式
formatter = ticker.FormatStrFormatter("%.2f%%")

# 设置刻度格式
ax1.yaxis.set_major_formatter(formatter)

# 设置子刻度
# ax1.minorticks_on??

plt.show()

5.3 多图布局

5.3.1 调整子图间距

  • fig.subplots_adjust(left=None,bottom=None,right=None,top=None, wspace=None,hspace=None)
  • 使用 fig.tight_layout(h_pad=None,w_pad=None)
def plot_fig(ax):
    ax.plot([1,2],[1,2])
    ax.set_xlabel("x-label")
    ax.set_ylabel("y-label")
    ax.set_title("title")
    
    
fig,axes = plt.subplots(2,2)
plot_fig(axes[0,0])
plot_fig(axes[0,1])
plot_fig(axes[1,0])
plot_fig(axes[1,1])

# wspace:width space  hspace:height space 
# fig.subplots_adjust(wspace=1,hspace=1)

# 自动调整
fig.tight_layout()

# h_pad:height padding w_pad:width padding
# fig.tight_layout(h_pad=10,w_pad=5)

plt.show()

在这里插入图片描述

5.3.2 自定义布局

"""方法1:plt.subplot"""
plt.figure()
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)

在这里插入图片描述

"""
方法2:fig.add_subplot
比较复杂的布局需要借助到 GridSpec对象,通过 fig.add_gridspec(2,2)
创建栅栏模式,再使用 fig.add_subplot 添加子图(下面举例了调整子图比例)

"""
fig = plt.figure()
width = (2,1)     # 宽为2:1 0列:1列 的宽度 2:1
height = (2,1)    # 高为2:1 0行:1行 的宽度 2:1
gs = fig.add_gridspec(2,2,width_ratios=width,height_ratios=height)

# [行,列]   [0,0]  取一整行 列取全部
fig.add_subplot(gs[0,:])
fig.add_subplot(gs[1,0])
fig.add_subplot(gs[1,1])

在这里插入图片描述

5.4 修改默认配置项

1.自定义:mytest.mplstyle
2.将该文件放置Python安装路径\Lib\site-packages\matplotlib\mpl-data\stylelib下
3.通过plt.style.use("mytest")使用自定义配置文件即可

# 使用自定义的配置文件
plt.plot(range(5),range(5))
plt.title("exersise")
plt.style.use("mytest") # 使用自定义的配置文件
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值