Matplotlob 简明实例入门

通过几个实例,快速了解matplotlib.pyplot 中最为常见的折线图,散点图,柱状图,直方图,饼图的用法

如果您需要更为详细的内容,请参考官方文档:

https://matplotlib.org/gallery/

import matplotlib.pyplot as plt
import random
from pylab import mpl
# 设置显示中文字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

案例1:显示温度变化状况

# 0.生成数据
x = range(60)
y_shanghai = [random.uniform(10, 15) for i in x] # 1.创建画布
plt.figure(figsize=(20,8), dpi=100) # 2.图形绘制
plt.plot(x, y_shanghai) ## 2.1添加x,y轴刻度
y_ticks = range(40)
x_ticks_labels = ['11点{}分'.format(i) for i in x] plt.xticks(x[::5], x_ticks_labels[::5])
plt.yticks(y_ticks[::5]) # 2.2 显示网格 ,True可以不给,后面有其他值默认为True
plt.grid(True, linestyle='--', alpha=0.7) # 2.3 添加描述信息
plt.xlabel('时间', fontsize=16)
plt.ylabel('温度', fontsize=16)
plt.title('中午温度变化图示', fontsize=20) # 3.保存图形
# plt.savefig('./data/temperature.png') # 4.图形展示, 会释放内存中的资源
plt.show()

案例2. 同一个坐标系中绘制多个图像

# 0.新增北京温度数据
x = range(60)
y_beijing = [random.uniform(1, 3) for i in x] # 1.创建画布
plt.figure(figsize=(20, 8), dpi=100) # 2.绘制折线图
# 2.1 绘制x, y刻度
x_ticks = ['11点{}分'.format(i) for i in x]
y_ticks = range(40) plt.xticks(x[::5], x_ticks[::5])
plt.yticks(y_ticks[::1]) # 2.2 绘制坐标轴描述
plt.xlabel('时间', fontsize=16)
plt.ylabel('温度', fontsize=16)
plt.title('北京上海两地温度变化图', fontsize=20) # 2.3 绘制网格线
plt.grid(True, linestyle='--', alpha=0.7) # 3 绘制图形
plt.plot(x, y_beijing, color='c', linestyle='-.',label='北京')
plt.plot(x, y_shanghai, color='m', linestyle='--',label='上海') # 4. 绘制图例, 需要在绘制图形时指定label
plt.legend(loc='best') # 5. 保存图片,需要在plt.show()释放内存资源之前
plt.savefig('./data/北京上海两地气温变化图.png') # 5.显示图像
plt.show()

案例3. 多个坐标系显示(子图)

# 0.获取数据
x = range(60)
y_beijing = [random.uniform(1, 5) for i in x]
y_shanghai = [random.uniform(15, 25) for i in x] # 1.创建画布
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 8), dpi=100) # 2.绘制图像
axes[0].plot(x, y_beijing, label='北京')
axes[1].plot(x, y_shanghai, label='上海', color='c', ls='--') # 2.1 绘制刻度
x_ticks_label = ['11点{}分'.format(i) for i in x]
y_ticks = range(40) # 先设定数据标签set_xticks, 然后再改为字符串set_xticklabels (不是xtickslabels !!)
axes[0].set_xticks(x[::5])
axes[0].set_xticklabels(x_ticks_labels[::5])
axes[0].set_yticks(y_ticks[::5]) axes[1].set_xticks(x[::5])
axes[1].set_xticklabels(x_ticks_labels[::5])
axes[1].set_yticks(y_ticks[::5]) # 2.2 设定网格显示
axes[0].grid(True, linestyle='--', alpha=0.5)
axes[1].grid(True, linestyle='-.', alpha=0.5) # 2.3 添加描述信息
axes[0].set_xlabel('时间', fontsize=16)
axes[0].set_ylabel('北京温度', fontsize=16)
axes[0].set_title('北京温度变化图', fontsize=20) axes[1].set_xlabel('时间', fontsize=16)
axes[1].set_ylabel('北京温度', fontsize=16)
axes[1].set_title('北京温度变化图', fontsize=20) # 2.4 添加图例
axes[0].legend(loc=0)
axes[1].legend(loc=0) # 3. 保存图像
plt.savefig('北京上海两地温度子图.png') # 4. 显示图像
plt.show()

案例4.常见其他图形绘制

4.1 散点图绘制

# 0.准备数据
x = [225.98, 247.07, 253.14, 457.85, 241.58, 301.01, 20.67, 288.64,
163.56, 120.06, 207.83, 342.75, 147.9 , 53.06, 224.72, 29.51,
21.61, 483.21, 245.25, 399.25, 343.35]
y = [196.63, 203.88, 210.75, 372.74, 202.41, 247.61, 24.9 , 239.34,
140.32, 104.15, 176.84, 288.23, 128.79, 49.64, 191.74, 33.1 ,
30.74, 400.02, 205.35, 330.64, 283.45] # 1. 创建画布
plt.figure(figsize=(20, 8), dpi=100) # 2.绘制散点图
plt.scatter(x, y) # 3. 显示图形
plt.show()

4.2 柱状图绘制

# 0. 准备数据(以某月电影票房为例)
movie_name = ['雷神3:诸神黄昏','正义联盟','东方快车谋杀案','寻梦环游记','全球风暴','降魔传','追捕','七十七天','密战','狂兽','其它']
# x, y 分别为电影名称和票房
x = range(len(movie_name))
y = [73853,57767,22354,15969,14839,8725,8716,8318,7916,6764,52222] # 1.创建画布
plt.figure(figsize=(20, 8), dpi=100) # 2.绘制柱状图
# 可以添加每个的宽度和颜色(列表输入)
plt.bar(x, y, width=0.5, color=['b','r','g','y','c','m','y','k','c','g','b']) # 2.1 修改x轴刻度
# plt.xticks(ticks=x, labels=movie_name) # ticks -> 原刻度, labels->新标签
plt.xticks(x, movie_name, fontsize=15) # 2.2 网格
plt.grid(ls='--', lw=1, alpha=0.5) # ls->linestyle, lw->linewidth # 2.4 添加标题和坐标轴名称
plt.title('电影票房对比')
plt.xlabel('电影名称')
plt.ylabel('上映票数') # 3.显示图像
plt.show()

4.3 直方图

# 0.生成数据
x = [random.uniform(0, 100) for i in range(200)] # 1.绘制图形
# 直方图用来表示数据的分布,横轴表示数据范围,总之表示分布情况, bins表示分组数量
# y轴表示每个组的占比(百分数)或者数量
plt.hist(x, bins=30) # 2.显示图形
plt.show()

4.4 饼状图

# 0.获取数据
# 以不同学科的成绩占比
label_names = ['语文', '数学', '外语', '政治', '物理'] # 每部分的占比(字段换算成百分比)
rate = [1,2,3,4,5] # 1.绘制图像
# autopct参数为显示占比百分数
plt.pie(rate, labels=label_names, colors=['b','r','g','c','pink'], autopct='%1.2f%%') plt.show() # 参考资料:
# https://matplotlib.org/gallery/pie_and_polar_charts/pie_features.html#sphx-glr-gallery-pie-and-polar-charts-pie-features-py

最新文章

  1. Apache日志配置详解(rotatelogs LogFormat)
  2. web通过ActiveX打印
  3. PHP给图片加文字(水印)
  4. Codeforces Round #334 (Div. 2) D. Moodular Arithmetic 环的个数
  5. 5、四大组件之一-Activity与Intent
  6. Docker contanier comunication with route
  7. Java NIO学习笔记一 Java NIO概述
  8. HDU 6200 2017沈阳网络赛 树上区间更新,求和
  9. 第二次作业:结对编程,四则运算的GUI实现
  10. 解决360随身wifi每天首连频繁断线
  11. Linux服务器断电导致挂载及xfs文件损坏的修复方法
  12. linux 命令 — archive
  13. 在Windows10中运行debug程序
  14. Spring boot 问题总结
  15. 小波学习之一(单层一维离散小波变换DWT的Mallat算法C++和MATLAB实现) ---转载
  16. ElasticSearch入门2: 基本用法
  17. tensorflow :ckpt模型转换为pytorch : hdf5模型
  18. django从请求到返回都经历了什么[转]
  19. jquery mobile 移动web(4)
  20. winds dlib人脸检测与识别库

热门文章

  1. 阿里云ECS 实例Centos7系统磁盘扩容
  2. Protobuf 简介及简单应用
  3. 使用python抓取汽车之家车型数据
  4. Python——2list和tuple类型
  5. React之mockjs+sass+生命周期函数
  6. 配置github——每次提交后使contributions有记录(有小绿格子)
  7. 使用timeit测试Python函数的性能
  8. Keras在MNIST实现LeNet-5模型训练时的错误?
  9. vue 打包体积过大 实现懒加载 ????
  10. iview的render函数使用