当前位置: 首页 > news >正文

Python之三大基本库——Matplotlib

好久没来总结了,今天刚好有时间,我们来继续总结一下python中的matplotlib

一、什么是Matplotlib

‌Matplotlib‌是一个Python的2D绘图库,主要用于将数据绘制成各种图表,如折线图、柱状图、散点图、直方图、饼图等。它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形,使得数据可视化更加直观和具有说服力‌

(简单来说呢就是画图工具,用来展示数据的变化趋势等,其中最重要的模块是pyplot)

(在这里再简单提一下python中另外两个常用的图形展示库,Seaborn和Plotly,有兴趣的小伙伴可以自行去了解一下:Matplotlib:基础且灵活的可视化库;Seaborn:美观且统计导向的可视化库; Plotly:交互性强的可视化库)

官网地址:Matplotlib — Visualization with Python

二、Matplotlib的作用和功能

Matplotlib的主要作用包括:

  1. 数据可视化‌:通过Matplotlib,开发者可以轻松地将数据绘制成各种图表,帮助用户“看见数据”的趋势、规律和异常值,从而更好地理解和分析数据‌2。
  2. 跨平台支持‌:Matplotlib支持多种操作系统和图形界面,能够在不同的平台上生成高质量的图形‌3。
  3. 丰富的图表类型‌:Matplotlib提供了丰富的图表类型,包括折线图、柱状图、散点图、直方图、饼图等,满足各种数据可视化的需求‌12。
  4. 简单易用:Matplotlib的API设计类似于MATLAB,使得用户可以快速上手并使用其进行数据可视化‌

三、Matplotlib中的基本使用方法

1、下载安装

# 可以通过-i 指定国内镜像,安装更快速
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple# 也可以使用anaconda的方法安装,其中可以通过conda-forge通道安装最新版本
conda install -c conda-forge matplotlib

2、导入引用

from matplotlib import pyplot as plt
import matplotlib

四、画图示例

通过学习呢,发现matplotlib是比较好上手的,加上现在AI的技术都比较成熟,在这里我就不过多的进行讲解了,就讲解一些比较简单的基本示例和一些需要注意的地方,在代码中会有标注,都是比较好理解的,如果大家没有任何基础,可以参考下面这位博主的文章,各个属性总结的比较全面Matplotlib-CSDN博客

1、中文格式转变

matplotlib是默认不支持中文的,所以当我们在轴刻度、轴标签、标题、图例等等中需要用到中文的画就需要先进行转变

其中苹果系统、linux和window中的方式可能会有一下不同,大家可以把方法都试一下,看看哪种生效使用哪种方法

import matplotlib# 支持中文格式方法一(全局生效)
font = {'family':'Microsoft YaHei','weight':'bold','size':'10'}
matplotlib.rc('font',**font)
matplotlib.rc('font',family='Microsoft YaHei',weight='bold',size='10')# 支持中文的字体格式方法二(全局生效)
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 推荐
plt.rcParams['font.sans-serif'] = ['SimHei']  # 黑体
# 解决负号显示问题
plt.rcParams['axes.unicode_minus'] = False# 支持中文的字体格式方法三(局部,一般不推荐上面两个没有效果再使用)
# 在使用这种方法之前还需要查询电脑安装的支持中文的语言
import matplotlib
import fontManager, FontProperties
# 查看matplotlib文件地址
print(matplotlib.matplotlib_fname()) 
from matplotlib.font_manager import fontManager
import matplotlib.pyplot as plt# window查看系统所有可用字体
fonts = [font.name for font in fontManager.ttflist if 'hei' in font.name.lower() or 'song' in font.name.lower()]
print("可用中文字体:", fonts)
# linux 查看系统可用字体 fc-list命令# 查询出来后放在FontProperties里面指定参数,如下
chinese_font = FontProperties(fname='simhei.ttf', size=12)  
plt.title("中文标题", fontproperties=chinese_font)  # 仅当前标题生效
plt.xlabel("X轴", fontproperties=chinese_font)

2、最简单的图

from matplotlib import pyplot as plt
x = range(2,26,2)
y = [15,13,14.5,16,19,17,19,20,25,28,29,18]
plt.plot(x,y)
plt.show()

 

设置画布大小,清晰度,X\Y轴刻度值、保存成图片

# figsize画布大小,dpi像素点清晰度
fig = plt.figure(figsize=(20,8),dpi=80)
plt.plot(x,y)
# 设置X轴刻度
plt.xticks(x)
# 设置Y轴刻度
plt.yticks(range(min(y),max(y)+1))
# 保存成图片到当前目录下
plt.savefig('test_size.png')
plt.show()

其它相关属性,图例、标签、透明度设置

import matplotlib.pyplot as plt
import numpy as np# 生成示例数据
x = np.linspace(0, 10, 20)
y = np.sin(x)
# y1 = range(-1,1,20)
y1 = np.random.uniform(-1, 1, 20)
# 绘制带标记的线条
plt.plot(x, y, '^:', color='blue', label='哈哈')  # 'o-' 表示圆形标记和实线
plt.plot(x, y1, 'o-', color='red', label='嘻嘻') 
# 常见的格式字符串 'o-':
# o 表示圆形标记。
# - 表示实线。
# 其他常见标记:^(三角形)、s(方形)、*(星形)等。
# 其他常见线条:--(虚线)、:(点线)等。
# 添加图例和标签
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Plot with Points and Line')
plt.legend(loc=10)
# 网格及其透明度
plt.grid(alpha = 0.5)# 显示图形
plt.show()

3、散点+线性相关图

from matplotlib  import pyplot as plt
import numpy as np
# 散点+线性相关图 :对比三月份和十月份温度变化的对比
y3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y10 = [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]x3 = range(1,32)
x10 = range(35,66)
plt.figure(figsize=(15,7),dpi=80)
plt.scatter(x3,y3,label='3月', color='orange')
plt.scatter(x10,y10,label ='10月', color='blue')
# 计算线性回归线 (y = kx + b)
def fit_line(x, y):k, b = np.polyfit(x, y, 1)  # 1表示线性拟合return k * x + bline3 = fit_line(x3, y3)
line10 = fit_line(x10, y10)
plt.plot(x3, line3, color='orange', linestyle='-', alpha=0.7, label='3月趋势线')
plt.plot(x10, line10, color='blue', linestyle='-', alpha=0.7, label='10月趋势线')# bbox_to_anchor 控制图例的位置(参数表示位数);borderaxespad控制图例与坐标轴边框的距离
plt.legend(loc='upper right',bbox_to_anchor=(1, 1.1), borderaxespad=0)
x_ = list(x3) + list(x10)
_xtick_lable = ['3月{}日'.format(i) for i in x3]
_xtick_lable += ['10月{}日'.format(i) for i in range(1,32)]plt.xlabel('日期')
plt.ylabel('温度')
plt.title('3月份与10月份温度变化对比')
plt.xticks(x_,_xtick_lable,rotation=50)
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 推荐
plt.rcParams['axes.unicode_minus'] = False  
# 自动调整子图参数,防止图例被截断
plt.tight_layout()
plt.show()

4、条形对比图

from matplotlib import pyplot as plt
import numpy as np# 数据准备
y3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y10 = [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]
days = np.arange(1, 32)  # 日期(1-31日)# 创建图形
plt.figure(figsize=(15, 7), dpi=100)# 设置条形宽度和位置
bar_width = 0.35
x3_pos = days - bar_width/2  # 3月条形位置(左移半个宽度)
x10_pos = days + bar_width/2  # 10月条形位置(右移半个宽度)# 绘制条形图
bars3 = plt.bar(x3_pos, y3, width=bar_width, color='skyblue', edgecolor='navy', label='3月')
bars10 = plt.bar(x10_pos, y10, width=bar_width, color='salmon', edgecolor='darkred', label='10月')# 添加数据标签(可选)
def add_labels(bars):for bar in bars:height = bar.get_height()plt.text(bar.get_x() + bar.get_width()/2., height,f'{height}',ha='center', va='bottom', fontsize=8)add_labels(bars3)
add_labels(bars10)# 设置图表标题和坐标轴
plt.title('3月与10月每日温度对比', fontsize=16, pad=20)
plt.xlabel('日期', fontsize=12)
plt.ylabel('温度(℃)', fontsize=12)
plt.xticks(days, [f'{i}日' for i in days], rotation=45)
plt.ylim(0, 30)  # 固定y轴范围便于比较# 添加图例和网格
plt.legend(loc='upper right', bbox_to_anchor=(1.12, 1))
plt.grid(axis='y', linestyle='--', alpha=0.5)# 调整布局
plt.tight_layout()# 显示图形
plt.show()

5、柱状图(条形图)和横向条形图

import matplotlib.pyplot as plt# 数据准备
movies = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:\n最后的骑士","摔跤吧!爸爸","加勒比海盗5:\n死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊",]
box_office = [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]# 创建图形(调整宽度适应长文本)
plt.figure(figsize=(12, 6))# 绘制普通垂直条形图
bars = plt.bar(movies, box_office, width=0.6, color='steelblue', edgecolor='black')# 添加数据标签
plt.bar_label(bars, labels=[f"{x}亿" for x in box_office], padding=3, fontsize=9)# 自定义x轴标签(缩短名称并旋转)
short_names = [name[:15]+"..." if len(name)>15 else name for name in movies]
plt.xticks(range(len(movies)), short_names, rotation=45, ha='right')# 设置图表标题和坐标轴
plt.title("电影票房排行榜(单位:亿元)", fontsize=14, pad=20)
plt.ylabel("票房(亿元)", fontsize=12)
plt.ylim(0, 60)
plt.grid(axis='y', linestyle='--', alpha=0.5)# 调整边距防止标签被裁剪
plt.tight_layout()plt.show()

import matplotlib.pyplot as plt
import numpy as np# 数据准备
movies = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊"]
box_office = [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]# 创建横向条形图(更适合长文本标签)
plt.figure(figsize=(10, 12))
plt.barh(movies[::-1], box_office[::-1], height=0.6, color='#1f77b4', edgecolor='darkblue')plt.rcParams['font.sans-serif'] = ['Microsoft YAhei']
plt.rcParams['axes.unicode_minus'] = False
# 添加数据标签
for i, (name, value) in enumerate(zip(movies[::-1], box_office[::-1])):plt.text(value + 0.5, i, f'{value}亿', va='center', fontsize=10)# 图表装饰
plt.title('电影票房排行榜(单位:亿元)', fontsize=16, pad=20)
plt.xlabel('票房(亿元)', fontsize=12)
plt.xlim(0, 60)
plt.grid(axis='x', linestyle='--', alpha=0.6)# 调整布局
plt.tight_layout()
plt.show()

6、直方图

一种是自动设置间距,一种手动设置间距

import matplotlib.pyplot as plt
import numpy as np# 数据准备
durations = [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]# 创建画布
plt.figure(figsize=(12, 6))# 方法1:自动分组(使用 Freedman-Diaconis 规则计算最优bin宽度)
q25, q75 = np.percentile(durations, [25, 75])
iqr = q75 - q25
bin_width = 2 * iqr / (len(durations) ** (1/3))
bin_count = int((np.max(durations) - np.min(durations)) / bin_width)plt.subplot(1, 2, 1)
plt.hist(durations, bins=bin_count, edgecolor='black', color='skyblue')
plt.title(f"自动分组 (Freedman-Diaconis)\nbins={bin_count}")
plt.xlabel("电影时长(分钟)")
plt.ylabel("电影数量")
plt.grid(axis='y', alpha=0.3)# 方法2:手动优化分组(基于数据分布观察)
# custom_bins = [70, 90, 110, 130, 150, 170]
custom_bins = (max(durations)-min(durations))//3
plt.subplot(1, 2, 2)
plt.hist(durations, custom_bins)
plt.title(f"手动分组 \n bins={custom_bins}")
plt.xlabel("电影时长(分钟)")
plt.ylabel("电影数量")
plt.grid(axis='y', alpha=0.3)# 添加整体统计信息
mean_duration = np.mean(durations)
median_duration = np.median(durations)
plt.suptitle(f"电影时长分布分析\n(均值={mean_duration:.1f}分钟, 中位数={median_duration}分钟)", y=1.05, fontsize=12)plt.tight_layout()
plt.show()

设置直方图统计的刻度值与X轴分割线一致

# 绘制直方图
plt.figure(figsize=(10, 6))
# counts, _, patches = 
plt.hist(durations, (max(durations)-min(durations))//13, edgecolor='black', color='blue')# 关键设置:将刻度位置设为分区边界,并应用标签
plt.xticks(range(min(durations),max(durations)+13,13))
# 可选:添加分区说明(如箭头标注区间范围)
# for i in range(len(bins)-1):
#     plt.annotate(f"{bins[i]}-{bins[i+1]}", 
#                 xy=((bins[i] + bins[i+1])/2, 0), 
#                 xytext=(0, 10), 
#                 textcoords='offset points',
#                 ha='center', 
#                 arrowprops=dict(arrowstyle="->"))plt.title("电影时长分布(刻度显示在分区边缘)")
plt.xlabel("时长分区边界(分钟)")
plt.ylabel("电影数量")
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()

 

7、饼状图

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题# 数据
categories = ['电子产品', '服装', '食品', '日用品', '其他']
sales = [4500, 3000, 2500, 1500, 800]
explode = (0.1, 0, 0, 0, 0)  # 突出显示第一部分# 绘制饼图
fig, ax = plt.subplots(figsize=(10, 7))
wedges, texts, autotexts = ax.pie(sales, explode=explode, labels=categories, autopct='%1.1f%%',shadow=True, startangle=140,colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0']
)# 设置文本属性
plt.setp(autotexts, size=10, weight="bold")
ax.set_title('商品销售占比分析', fontsize=16, pad=20)# 添加图例
ax.legend(wedges, categories,title="商品类别",loc="center left",bbox_to_anchor=(1, 0, 0.5, 1))plt.tight_layout()
plt.show()

 

8、环状饼状图

import matplotlib.pyplot as plt# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']# 数据
labels = ['学习', '工作', '娱乐', '运动', '社交']
time = [8, 10, 3, 1, 2]# 绘制环形饼图
fig, ax = plt.subplots(figsize=(8, 8))
ax.pie(time, labels=labels, autopct='%1.1f%%', startangle=90, pctdistance=0.85,colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0'])# 添加中心圆
centre_circle = plt.Circle((0,0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)ax.set_title('每日时间分配', fontsize=16)
plt.tight_layout()
plt.show()

 

好了,我们matplotlib在这里就不多做总结了,都是比较简单的示例,大家了解就好,更多的会在实际应用中加深印象 

下面有时间会继续更新pyhon中的最后一个库Pandas库,大家可以关注收藏一下哦

相关文章:

  • 对称二叉树的判定:双端队列的精妙应用
  • 源码:处理文件格式和字符集的相关代码(3-3)
  • Spring WebFlux与Quarkus实战:云原生微服务开发的两大主流框架深度解析
  • 一分钟了解机器学习
  • Linux系统启动相关:vmlinux、vmlinuz、zImage,和initrd 、 initramfs,以及SystemV 和 SystemD
  • 割点与其例题
  • 消防应急处置管理的全流程概述
  • NLP双雄争霸:GPT与BERT的生成-理解博弈——从技术分野到产业融合的深度解码
  • C++:单例模式
  • 【数据仓库面试题合集①】数据建模高频面试题及解析
  • 索恩格汽车SEG Automotive EDI 需求分析
  • Unity3D 游戏编程内存优化技巧
  • linux下tcp/ip网络通信笔记1,
  • Android 中 显示 PDF 文件内容(AndroidPdfViewer 库)
  • 7. 进程控制-进程替换
  • 科技项目验收测试对软件产品和企业分别有哪些好处?
  • 填孔即可靠:猎板PCB如何用树脂塞孔重构高速电路设计规则
  • 安装Minikube
  • 芍药BAHD酰基转移酶-文献精读128
  • Vue2项目created不执行
  • 梅花奖在上海|湘剧《夫人如见》竞梅,长沙文旅来沪推广
  • 陕西省市监局通报5批次不合格食品,涉添加剂超标、微生物污染等问题
  • 时隔三年,俄乌直接谈判重启
  • 俄乌谈判开始
  • 再现五千多年前“古国时代”:凌家滩遗址博物馆今开馆
  • 音乐节困于流量