前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Matplotlib 使用笔记

Matplotlib 使用笔记

作者头像
村雨遥
发布2022-06-15 09:26:37
3280
发布2022-06-15 09:26:37
举报
文章被收录于专栏:JavaParkJavaPark

什么是Matplotlib

引用维基百科中的定义,Matplotlib 是 Python 编程语言及其数学扩展包 Numpy 的可视化操作界面。通过利用 Tkinter、wxPython、QT、GTK+ 等通用图形用户界面工具包,为应用程序嵌入式绘图提供了 API。此外,它还有一个基于图像处理库的pylab接口,其设计与 Matlab 十分相似;

如何使用Matplotlib

我将通过代码实例的形式给出Matplotlib的使用方法,具体情况如下:

代码语言:javascript
复制
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/21 9:59
# @Author  : Cunyu
# @Site    : cunyu1943.github.io
# @File    : matplotlib_examples.py
# @Software: PyCharm

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

"""
基本使用
"""
x = np.linspace(-5, 5, 100)
y1 = 2 * x +5
y2 = x ** 2

# 定义一个图像窗口,并画出图像
plt.figure(num=1, figsize=(8,5))
plt.plot(x, y1, label = 'linear', color = 'red', linestyle='--')
plt.plot(x, y2, label = 'square', color = 'blue')

# 调整坐标轴名字及其间隔
plt.ylim(-5, 20)
plt.xlim(-5, 5)
plt.xlabel('x')
plt.ylabel('y')

# 设置坐标轴刻度及对应名
new_ticks = np.linspace(-5, 4, 10)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-3, -1, 3, 10, 18],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

# 获取坐标轴信息
ax = plt.gca()

# 设置边框信息,将上边框和右边框设置为不同颜色,默认是白色
ax.spines['right'].set_color('green')
ax.spines['top'].set_color('purple')

# 调整坐标轴位置
ax.spines['left'].set_position(('data', 1))
ax.spines['bottom'].set_position(('data', 0))

"""
Legend图例,添加图例
添加位置参数:
 'best' : 0,          
 'upper right'  : 1,
 'upper left'   : 2,
 'lower left'   : 3,
 'lower right'  : 4,
 'right'        : 5,
 'center left'  : 6,
 'center right' : 7,
 'lower center' : 8,
 'upper center' : 9,
 'center'       : 10,
"""
plt.legend(loc = 'upper right') # 显示在右上角

# 添加注释
plt.text(0, 0, r'This is (0, 0).', fontdict={'size':14, 'color':'red'})
# 显示图像
plt.show()
plt.close()

"""
画图种类
"""
# 散点图
SIZE = 1024
x = np.random.normal(0, 1, SIZE)
y = np.random.normal(0, 1, SIZE)
T = np.arctan2(y, x)
plt.scatter(x, y, s=75, c=T, alpha=.5)
plt.show()
plt.close()

# bar柱状图
x = np.arange(15)
Y1 = (1 - x / float(15)) * np.random.uniform(0.5, 1.0, 15)
Y2 = (1 - x / float(15)) * np.random.uniform(0.5, 1.0, 15)
plt.bar(x, Y1, edgecolor ='black',facecolor='red')
plt.bar(x, -Y2, edgecolor ='yellow',facecolor='blue')
for x, y in zip(x,Y1):
    plt.text(x+0.1,y+0.1,'%.2f' % y, ha='center',va='bottom')
plt.show()
plt.close()

# 随机矩阵画图
a=np.array(np.random.rand(12)).reshape(3,4)
plt.imshow(a, interpolation='none', cmap='bone', origin='lower')
plt.colorbar(shrink=.1)
plt.xticks(())
plt.yticks(())
plt.show()
plt.close()

# 3D图
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(-5, 5, .5)
y = np.arange(-5, 5, .25)
x,y = np.meshgrid(x, y)
r = np.sqrt(x**2,y**2)
z=np.sin(r)
ax.plot_surface(x,y,z,cmap=plt.get_cmap('rainbow'),rstride=1,cstride=1)
# 投影
ax.contourf(x,y,z,zdir='y',offset=2,cmap=plt.get_cmap('rainbow'))
plt.show()
plt.close()

"""
多图合并显示
"""
# 1、subplot多合一显示
plt.figure()

# 将整个图像窗口均匀分为2行2列
plt.subplot(2,2,1)
plt.plot([0, 1], [0,1])
plt.subplot(2,2,2)
plt.plot([0, 1], [0,5])
plt.subplot(2,2,3)
plt.plot([0, 1], [0,10])
plt.subplot(2,2,4)
plt.plot([0, 1], [0,15])
plt.show()
plt.close()

# 将整个图像窗口不均匀划分
plt.subplot(2,1,1)
plt.plot([0, 1], [0,1])
plt.subplot(2,3,4)
plt.plot([0, 1], [0,5])
plt.subplot(2,3,5)
plt.plot([0, 1], [0,10])
plt.subplot(2,3,6)
plt.plot([0, 1], [0,15])
plt.show()
plt.close()

import matplotlib.gridspec as gridspec
# 2、subplot分格显示
plt.figure()
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:2])
ax3 = plt.subplot(gs[1:,2])
ax4 = plt.subplot(gs[-1,0])
ax5 = plt.subplot(gs[-1,-2])
plt.show()
plt.close()

# 3、图中图
# 数据准备
fig = plt.figure()
x = np.arange(6)
y = x**2
print(x)
print(y)

# 大图
ax1 = fig.add_axes([.1, .1, .8, .8])
ax1.plot(x,y,'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
# 小图
ax2 = fig.add_axes([.2,.5,.25,.25])
ax2.plot(y,x,'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
plt.show()
plt.close()

# 4、次坐标轴
# 第一个坐标轴y
x = np.arange(0, 10, 0.1)
y1 = x**2
y2 = -1 * y1
fig, ax1 = plt.subplots()
# 第二个坐标轴
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')   # green, solid line
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.plot(x, y2, 'b-') # blue
ax2.set_ylabel('Y2 data', color='b')
plt.show()
plt.close()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-12-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是Matplotlib
  • 如何使用Matplotlib
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档