Python系列 之 matplotlib库 基础知识

本文介绍了Python的matplotlib库,讲解了pyplot接口的基本使用,包括简单示例、中文显示问题的解决、Figure和Axes对象的创建及样式设置。还详细讨论了Axes对象的方法,如axis、cla、clear、grid等,以及轴标签、标题、图例的操作。同时涵盖了线宽、线型、标记大小等绘图样式,并给出了折线图和柱形图的绘制示例。
摘要由CSDN通过智能技术生成


matplotlib属于第三方库需要另外进行安装才可以使用

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib

Matplotlib将数据绘制在Figure对象上,Figure对象应包含一个或多个Axes对象,Axes对象包含一组X-Y坐标或者更多维度坐标的区域
pyplot是matplotlib的绘图接口;对Figure对象进行管理

官方教程

# import
import matplotlib.pyplot as plt

Pyplot

matplotlib.pyplot是使 matplotlib 可以像MATLAB一样工作的函数集合;每个pyplot函数都会对图形进行一些更改:例如,创建图形、在图形中创建绘图区域、在绘图区域中绘制一些线、用标签装饰绘图等;
pyplot的API调用通常不如面向对象的 API 灵活;pyplot大多数的函数调用也可以用Axes对象的方法调用实现

简单示例

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()

在这里插入图片描述

中文显示问题

注册全局字体

import matplotlib.pyplot as plt
# 注册全局字体
plt.rcParams['font.sans-serif'] = ['simsun']
# plt.rcParams['font.family'] = ['simsun']

font_manager.FontProperties注册字体

# 注册字体
from matplotlib.font_manager import FontProperties
font_simsun = FontProperties(fname="./fonts/simsun.ttc")
# plt.xlabel("X 轴", fontproperties=font_simsun)

Figure

Figure就像一张空白的纸张可以在上画上图表的内容

Figure的组成部分

在这里插入图片描述

创建Figure对象

fig = plt.figure() # 创建一个空白的Figure对象 不包含Axes对象
fig, ax = plt.subplots() # 创建包含一个Axes对象的Figure对象
fig, ax = plt.subplots(2, 3) # 创建包含一组Axes对象的Figure对象 一组 2*3 的Axes对象 2行3列
plt.show()

在这里插入图片描述

Axes

Axes对象的属性和方法定义了大多部分的绘制方法以及绘制样式
Axes对象基于在Figure对象上的绘制区域,通常包括两个(在3D情况下为三个)Axis对象

简单的例子

Axes对象的plot方法

import matplotlib.pyplot as plt
import numpy as np
fit, ax = plt.subplots()
# ax.plot方法绘制
# 将y与x绘制为线/标记
# Axes.plot(*args, scalex=True, scaley=True, data=None, **kwargs)
# plot([x], y, [fmt], *, data=None, **kwargs)
# plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
# 参数fmt是定义颜色、标记和线型等基本格式的便捷方法
# fmt = '[marker][line][color]'
# 可以将Line2D特性用作关键字参数
# Line2D属性URL:https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D
x = np.arange(10)
# 红色圆形标记虚线连接
ax.plot(x, 'ro--',label='Data_1')
ax.plot(x,x**2,label='Data_2', color='red',marker='o',linestyle='dashed')
# 设置X-Y坐标轴标签
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
# 设置title
ax.set_title("Title")
# 显示legend 图例
ax.legend()
plt.show()

在这里插入图片描述

设置样式

  • Colors
  • Linewidths
  • linestyles
  • markersizes

linewidths

# Linewidths
fig, ax = plt.subplots()
x = np.arange(0,10,0.1)
for width in range(1,5):
    ax.plot(x,x+width,linewidth=width)
    ax.text(x=10,y=10+width,s=f"width is {
     width}")
plt.show()

在这里插入图片描述

linestyles

linestyle description
‘-’ or ‘solid’ solid line
‘–’ or ‘dashed’ dashed line
‘-.’ or ‘dashdot’ dash-dotted line
‘:’ or ‘dotted’ dotted line
‘none’, ‘None’, ’ ', or ‘’ draw nothing
#linestyles
linestyle = {
   '-':'solid', '--' : 'dashed','-.' : 'dashdot',
             ':' : 'dotted','none':"None"}

fig, ax = plt.subplots()
x = np.arange(0,10,2)
y = np.ones(5)
dy = 0.0
for style, val in linestyle.items():
    ax.plot(x,y+dy,linestyle=val)
    ax.annotate(val,(8.0,1+dy))
    dy+=5
    
plt.show()

在这里插入图片描述

markersizes

marker description
‘.’ point
‘,’ pixel
‘o’ circle
‘v’ triangle_down
‘^’ triangle_up
‘<’ triangle_left
‘>’ triangle_ri
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值