python库之matplotlib库


一、简介:

1.安装

pip install matplotlib

2.import as

import matplotlib as mpl
import matplotlib.pyplot as plt

三、图的元素设置

总汇

功能函数参数
显示图片%matplot inline、%matplot notebook与plt.show()null
标签-图片plt.title()一般是字符串
标签-x坐标轴plt.xlabel()
标签-y坐标轴plt.ylabel()
网格plt.grid()必选参数True,可选参数color
边界-x轴plt.xlim()元组类型或是列表类型
边界-y轴plt.ylim()
刻度-x轴plt.xticks()列表类型,range(),np.arang()
刻度-y轴plt.yticks()
图例plt.legend()

设定整个画布的尺寸

设定整个画布的尺寸(产生一个新画布)

# 英寸
plt.figure(figsize=(3, 3))
"""
产生两个画布
"""
plt.figure(figsize=(3, 3))
plt.plot([0,1,2,3])

plt.figure(figsize=(3, 3))
plt.plot([3,2,1,0])

在这里插入图片描述

显示出来

%matplot inline%matplot notebookplt.show()】:

解释:

  • 这些都是用来显示绘制的图像的,只用打一个就行了。
  • plt.show()是各IDE通用的。
  • %matplot inline是专在Jupyter中用来自动显示图像的。将图像以静态方式显示。
  • %matplot notebook是专在Jupyter中用来自动显示图像的。将图像以动态方式显示。

例如:

  • Jupyter notebook的%matplot notebook:
    在这里插入图片描述
  • Jupyter notebook的%matplot inline:
    在这里插入图片描述
  • 其他IDE,如IDLE:
    在这里插入图片描述

工具Jupyter Notebook安装:

pip install jupyter

保存的图像分辨率

# 图片像素 
matplotlib.rcParams['figure.figsize']

# 分辨率 
matplotlib.rcParams['savefig.dpi']

# 保存图片,并指定分辨率
plt.savefig('plot123_2.png',dpi=200)

标题文字

区域函数
图片plt.title()
x坐标轴plt.xlabel()
y坐标轴plt.ylabel()
from matplotlib import pyplot as plt
x = [5,2,7]
y = [2,16,4]
plt.plot(x,y)
#图片的标题
plt.title('Image Title')
#坐标轴X轴
plt.xlabel('X axis')
#坐标轴Y轴
plt.ylabel('Y axis')
plt.show()

显示中文标题

将上这些

#coding=utf-8
from pylab import *
mpl.rcParams['font.sans-serif'] = ['SimHei']
#更改字体
mpl.rcParams['axes.unicode_minus'] = False
#解决更改字体导致显示不出负号的后遗症

图例

plt.legend()

在这里插入图片描述

网格

from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
#显示网格
#必选参数True,可选参数color
plt.grid(True,color='blue')
plt.show()

在这里插入图片描述

边界

限定数据显示的部分:a~b,包括b的

from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
# 方式一:元组类型
plt.xlim((4,12))
# 方式二:列表类型
plt.ylim([5,20])
plt.show()

在这里插入图片描述

刻度

注意:plt.plot(x, y)要放在plt.xticks()前面才有用。

import numpy as np
from matplotlib import pyplot as plt
x = [5, 8, 10]
y = [12, 16, 6]
plt.plot(x, y)

plt.xticks(range(4,12))      # 列表类型
plt.yticks(np.arange(5, 20, 1.5))           # numpy的ndarray类型
# 内置的range()函数生成的整数数列也行,plt.yticks(range(3,20))
# 但range()只能生成整数数列,而不如np.arange()可以生成浮点数数据
plt.show()

在这里插入图片描述

只是标注轴上的刻度,并不能代替边界,不想见到的数据还是会出现

import numpy as np
from matplotlib import pyplot as plt
x = [5,8,10]
y = [12,16,6]
plt.plot(x,y)
plt.xticks([7,8,9,10,11])
plt.yticks(np.arange(5,20,1.5))
plt.show()

在这里插入图片描述

刻度精度

设置刻度的小数位数即精度

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
x = [5, 8, 10]
y = [12, 16, 6]
plt.plot(x, y)

plt.xticks(range(4,12))      # 列表类型
plt.yticks(np.arange(5, 20, 1.5))     # numpy的ndarray类型
plt.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%.3f')) # x轴
plt.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('%.3f')) # y轴
plt.show()

在这里插入图片描述

刻度密度问题

方法1:直接少填几个显示出来的刻度xticks就行

import numpy as np
from matplotlib import pyplot as plt
x = [5, 8, 10]
y = [12, 16, 6]
plt.plot(x, y)

plt.xticks([4, 8, 12])      # 列表类型
plt.yticks(np.arange(5, 20, 1.5))           # numpy的ndarray类型
plt.show()

在这里插入图片描述
方法2:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
x = [5, 8, 10]
y = [12, 16, 6]
plt.plot(x, y)

plt.xticks(range(4,13))      # 列表类型
plt.yticks(np.arange(5, 20, 1.5))     # numpy的ndarray类型
tick_spacing = 4
plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
plt.show()

绘图风格

  • 使用plt.style.use('')设定风格:
  • 使用plt.style.available显示库中的风格:如ggplotfivethirtyeightdark_backgroundgrayscale
    在这里插入图片描述

绘制图片

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

# 设定整个画布的尺寸
plt.figure(figsize=(7, 7))

data = np.random.randint(0, 256, (10, 10, 3))

# 绘制10*10像素的
plt.subplot(4, 2, 1)
plt.imshow(data)

# R红色单通道
plt.subplot(4, 2, 3)
plt.imshow(data[:, :, 0])

# R红色的映射灰度
plt.subplot(4, 2, 4)
plt.imshow(data[:, :, 0], cmap='gray')

# G绿色单通道
plt.subplot(4, 2, 5)
plt.imshow(data[:, :, 1])

# G绿色的映射灰度
plt.subplot(4, 2, 6)
plt.imshow(data[:, :, 1], cmap='gray')

# B蓝色单通道
plt.subplot(4, 2, 7)
plt.imshow(data[:, :, 2])

# B蓝色的映射灰度
plt.subplot(4, 2, 8)
plt.imshow(data[:, :, 2], cmap='gray')

# 显示画布
plt.show()

在这里插入图片描述

绘制子图

python库matplotlib之plt画子图

四、图的类型

折线图plt.plot

import matplotlib.pyplot as plt

markers = {
    '.': 'point',
    ',': 'pixel',
    '^': 'triangle_up', 
    '<': 'triangle_left', 
    '>': 'triangle_right',  
    '+': 'plus', 
    '|': 'vline', 
    '_': 'hline', 
    '*': 'star', 
    'd': 'thin_diamond', 
    'D': 'diamond',
    'h': 'hexagon1', 
    'H': 'hexagon2', 
    'p': 'pentagon', 
    'P': 'plus_filled', 
    'x': 'x', 
    'X': 'x_filled', 
    's': 'square',
    'o': 'circle',
    'v': 'triangle_down',
    '1': 'tri_down', 
    '2': 'tri_up', 
    '3': 'tri_left', 
    '4': 'tri_right', 
    '8': 'octagon', 
    0: 'tickleft', 
    1: 'tickright', 
    2: 'tickup', 
    3: 'tickdown', 
    4: 'caretleft',
    5: 'caretright', 
    6: 'caretup', 
    7: 'caretdown', 
    8: 'caretleftbase', 
    9: 'caretrightbase', 
    10: 'caretupbase', 
    11: 'caretdownbase', 
    'None': 'nothing', 
    None: 'nothing', 
    ' ': 'nothing', 
    '': 'nothing'
}

plt.figure(figsize=(8, 15))
plt_index = 1
for maker in markers:
    y = [1, 3, 10, 2, 5]
    plt.subplot(9, 5, plt_index)
    plt.plot(y, marker=maker)			# here
    plt.title('[{}]'.format(maker))
    plt_index += 1
plt.tight_layout()
plt.savefig('plot123_2.png', dpi=300)

在这里插入图片描述

散点图

import matplotlib.pyplot as plt

markers = {
    '.': 'point',
    ',': 'pixel',
    '^': 'triangle_up', 
    '<': 'triangle_left', 
    '>': 'triangle_right',  
    '+': 'plus', 
    '|': 'vline', 
    '_': 'hline', 
    '*': 'star', 
    'd': 'thin_diamond', 
    'D': 'diamond',
    'h': 'hexagon1', 
    'H': 'hexagon2', 
    'p': 'pentagon', 
    'P': 'plus_filled', 
    'x': 'x', 
    'X': 'x_filled', 
    's': 'square',
    'o': 'circle',
    'v': 'triangle_down',
    '1': 'tri_down', 
    '2': 'tri_up', 
    '3': 'tri_left', 
    '4': 'tri_right', 
    '8': 'octagon', 
    0: 'tickleft', 
    1: 'tickright', 
    2: 'tickup', 
    3: 'tickdown', 
    4: 'caretleft',
    5: 'caretright', 
    6: 'caretup', 
    7: 'caretdown', 
    8: 'caretleftbase', 
    9: 'caretrightbase', 
    10: 'caretupbase', 
    11: 'caretdownbase', 
    'None': 'nothing', 
    None: 'nothing', 
    ' ': 'nothing', 
    '': 'nothing'
}

plt.figure(figsize=(8, 15))
plt_index = 1
for maker in markers:
    y = [1, 3, 10, 2, 5]
    plt.subplot(9, 5, plt_index)
    plt.scatter(range(len(y)), y, marker=maker)		# here
    plt.title('[{}]'.format(maker))
    plt_index += 1
plt.tight_layout()
plt.savefig('plot123_2.png', dpi=300)

在这里插入图片描述


Reference

官方Tutorial

Matplotlib官网的User’s Guide

Matplotlib官网的Gallery

Python第三方库matplotlib(2D绘图库)入门与进阶

Learning Scientific Programming with Python第七章matplotlib

  • 4
    点赞
  • 67
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值