matplotlib.pyplot画图入门教程,满足你的可视化需求

matplotlib画图的基本步骤

  1. 准备数据
  2. 创建图形
  3. 绘图
  4. 自定义设置
  5. 保存图形
  6. 显示图形

一.准备数据:首先介绍Numpy的基本使用

import numpy as np
# arange([start,] stop[, step,], dtype=None)
# start:开始位置
# stop:结束位置
# step:步长 默认值为1
# dtype:是数据的数据类型
np.arange(0, 10, 2) # array([0, 2, 4, 6, 8])
# linspace(start, stop, num=50)
# start:开始位置
# stop:结束位置
# num:将这个区间的数据分成的份数
np.linspace(0,5,6) # array([0., 1., 2., 3., 4., 5.])
'''
numpy中的常用数学函数
np.sin(x)
np.cos(x)
np.tax(x)
np.tan(x)
np.arctan(x)
np.arcsin(x)
np.arccos(x)
np.cosh(x)
np.sinh(x) 
np.power(x, num) # 指数函数
np.exp()
numpy常用的统计函数
np.sum()	# 计算数组中的和
np.mean()	# 计算数组中的均值
np.var()	# 计算数组中的方差
np.std()	# 计算数组中的标准差
np.max()	# 计算数组中的最大值
np.min()	# 计算数组中的最小值
np.argmax()	# 返回数组中最大元素的索引
np.argmin()	# 返回数组中最小元素的索引
np.cumsum()	# 计算数组中所有元素的累计和
np.cumprod()	# 计算数组中所有元素的累计积

'''

一.准备数据:下面详细介绍一下本文章会用到的函数

import numpy as np
#np.random.rand() # 通过本函数可以返回一个或一组服从“0~1”均匀分布的随机样本值。随机样本取值范围是[0,1),不包括1。
np.random.rand(5) #中间参数是维度
# array([0.00376725, 0.86551634, 0.46209527, 0.90981707, 0.95083522])
np.random.rand(3,2)
''''
array([[0.8530637 , 0.27165418],
       [0.50043972, 0.3180998 ],
       [0.35343743, 0.27305431]])
'''
# np.random.rand和上面函数的用法是一样的只不过使用的事正态函数

#np.random.randint(low, high=None, size=None, dtype='l')
np.random.randint(1,10,(5,5))
'''
array([[1, 5, 3, 2, 7],
       [9, 1, 1, 1, 4],
       [1, 1, 6, 2, 1],
       [2, 2, 7, 4, 4],
       [5, 6, 1, 9, 6]])
       在1-10中随机生成一个5x5的整数数组,不包括10
'''
np.random.random(size = (2,3)) # 只有size维度一个参数
'''
array([[0.06216955, 0.14071454, 0.97819655],
       [0.27906953, 0.38512329, 0.22541471]])
'''

二.创建图形–常见图形的设计

标题:线形图

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,50)
np.random.seed(1)
y = np.random.random(50)
plt.plot(x, y, linestyle = '-', linewidth = 2, color = 'deeppink')
plt.show()# 展示图形

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,50)
np.random.seed(1)
y = np.random.random(50)
plt.plot(x, y, linestyle = '--', linewidth = 2, color = 'deeppink', label = "demo")
plt.legend(loc=2) # 显示label 如果没有这句话不能显示demo 默认显示在右上方
'''
plt.legend([loc = integer])
默认是显示在最好的位置,自己也可以进行选择integer的值 :如下:
                Location String   Location Code
                ===============   =============
                '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.show()

在这里插入图片描述

标题:点状图

from matplotlib import pyplot as plt
import numpy as np
x = np.random.random(1000)

y = np.random.random(1000)
s = np.random.random(1000)*100
c = np.random.random(1000)
# 下面的点状图scatter的参数及意义
# x,y:表示数据的位置
# s:表示图形的大小
# c:表示颜色或颜色序列,可能的情况如下:
# 单一颜色
# 颜色序列
# 使用cmap映射到颜色的序列数
# 一个行为RGB的2-D数组
# marker:绘出的图形的形状,具有多种风格
# edgecolors = 'pink',
# cmap:默认为no
# norm:描述数据亮度,默认为no
# vmin,vmax:亮度设置,默认为no
# alpha = 0.5 # 范围为0-1
# linewidths:描边的宽度
# edgecolors:描边颜色
plt.scatter(x, y, s,
            # c,
            marker='v',
            # alpha=0.5,
            linewidths = 1, color = 'red')
            # 如果使用了color就是同一种颜色 但是就不能使用c参数,两种只能使用一个
plt.show()

在这里插入图片描述

from matplotlib import pyplot as plt

import numpy as np

#解决中文显示问题
# plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
# plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

x = np.random.random(1000)

y = np.random.random(1000)
s = np.random.random(1000)*100
c = np.random.random(1000)

plt.scatter(x, y, s,
            c,
            marker='v',
            # alpha=0.5,
            linewidths = 1)
plt.title("demo 示例") # 增加标题 但是有中文乱码问题  将上面的语句注释取消就行
plt.show()


在这里插入图片描述

from matplotlib import pyplot as plt

import numpy as np

plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

x = np.random.random(1000)

y = np.random.random(1000)
s = np.random.random(1000)*100
c = np.random.random(1000)

plt.scatter(x, y, s,
            c,
            marker='v',
            # alpha=0.5,
            linewidths = 1)
plt.title("demo 示例")
plt.show()

在这里插入图片描述

标题:线形图

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
Date = pd.date_range("20200223", periods = 6)
date = [x.__str__().split()[0] for x in Date]
# date就是得到一个日期如果不懂可以不用管
y = np.random.randint(1,10,(6,))
x = np.arange(1,7)
plt.bar(date, y, color = 'orchid', width = 0.5, bottom = 5, align='center', linewidth = 10)
# plt.xticks(date,rotation = 10)
plt.show()

在这里插入图片描述
下面的日期可能比较拥挤
可以加入plt.xtickets()转换角度

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
Date = pd.date_range("20200223", periods = 6)
date = [x.__str__().split()[0] for x in Date]
y = np.random.randint(1,10,(6,))
x = np.arange(1,7)
plt.bar(date, y, color = 'orchid', width = 0.5, bottom = 5, align='center', linewidth = 10)
plt.xticks(date,rotation = 10) # rotation就是字符串旋转的角度
plt.show()

在这里插入图片描述

横向的条形图也是一样的知识函数不一样而已,它使用的事plt.barh()

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
Date = pd.date_range("20200223", periods = 6)
date = [x.__str__().split()[0] for x in Date]
y = np.random.randint(1,10,(6,))
x = np.arange(1,7)
plt.bar(x, date, color = 'orchid')
plt.yticks(date,rotation = 10)
plt.show()

在这里插入图片描述

网格设计

import matplotlib.pyplot as plt

import numpy as np

if __name__=='__main__':
    plt.rcParams['font.sans-serif'] = ['KaiTi']  # 指定默认字体
    plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
    x1 = np.random.random(50)
    y1 = np.random.random(50)
    s1 = np.array([0.2]*50)*250
    c1 = np.array(['darkorange']*50)

    x2 = np.random.random(50)
    y2 = np.random.random(50)
    s2 = np.array([0.4] * 50)*250
    c2 = np.array(['deeppink'] * 50)

    x3 = np.random.random(50)
    y3 = np.random.random(50)
    s3 = np.array([0.5] * 50)*250
    c3 = np.array(['skyblue'] * 50)

    x4 = np.random.random(50)
    y4 = np.random.random(50)
    s4 = np.array([0.7] * 50)*250
    c4 = np.array(['orchid'] * 50)
    # plt.subplots(221, axisbg = 'darkgrey')
    # plt.figure(facecolor='darkgrey', edgecolor='darkgrey')  # 得到画布和设置背景颜色
    plt.grid(color='r', linestyle='--', linewidth=1, alpha=0.5) # 设置栅格子
    plt.scatter(x1, y1, s1, c1, marker='x', label = "hu", linewidths=11)
    plt.scatter(x2, y2, s2, c2, marker='x', label = 'sun', linewidths=11)
    plt.scatter(x3, y3, s3, c3, marker='x', label = "he", linewidths=11)
    plt.scatter(x4, y4, s4, c4, marker='x', label = "luo", linewidths=11)
    plt.legend(loc = 1)
    plt.show()

在这里插入图片描述

三.子图的设计

通过一个例子来引入子图

from matplotlib import pyplot as plt
import numpy as np
# 设计本次图片的分辨率
plt.figure(dpi=200)
x = np.linspace(-5,5,1000)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.power(x, 5) + np.exp(x)
y4 = np.cosh(x)
plt.subplot(2,2,1)
plt.plot(x, y1, color = 'orchid', linestyle = '-', label = "y = sin(x)")
plt.legend()
plt.subplot(2,2,2)
plt.plot(x, y2, color = 'deeppink', linestyle = '-', label = "y = cos(x)")
plt.legend()
plt.subplot(2,2,3)
plt.plot(x, y3, color = 'darkorange', linestyle = '-', label = "y = tan(x)")
plt.legend()
plt.subplot(2,2,4)
plt.plot(x, y4, color = 'skyblue', linestyle = '-', label = "y = cosh(x)")
plt.plot(np.zeros(1000), y4, color = 'blue', linestyle = '-',linewidth = 2)
plt.plot(np.zeros(1000), -y4, color = 'blue', linestyle = '-',linewidth = 2)
plt.ylim(-60,60)
plt.legend()
plt.savefig('subplot-4.jpg', dpi=2000)
plt.show()

在这里插入图片描述

# 首先来看第一部分
plt.subplot(2,2,1)
# 后面两行很容易理解前面都有过解释,现在着重来看第一行
# subplot(nrows, ncols, index)
# 这里将画布分成2x2部分第一个是行第二个是列,index是第几部分
# 2x2就分成了四个部分如下:
'''
1    2
3    4
'''
# 其他的也是同样的原理从每一个plt.subplot开始到下一个
# plt.subplot截止是一个图形,他们之间相互独立
plt.plot(x, y1, color = 'orchid', linestyle = '-', label = "y = sin(x)")
plt.legend()

自定义设置(番外篇)

标题:如何去掉部分轴线
在这里插入图片描述

有两种方法如下

import matplotlib.pyplot as plt
import numpy as np
if __name__=='__main__':
    x = np.linspace(1,10,100)
    y = np.log(x)
    ax = plt.axes() # 得到一个坐标轴的设置类ax可以设置轴的情况
    ax.spines['top'].set_visible(False) # 设置是否可视
    ax.spines['right'].set_visible(False) # 其他的有left bottom
    plt.plot(x, y, color='green', # marker='o',
                  linestyle='dashed',
                linewidth=2, markersize=12)
    plt.show()
import matplotlib.pyplot as plt

import numpy as np

if __name__=='__main__':
    x = np.linspace(1,10,100)
    y = np.log(x)
    fig, ax = plt.subplots() # 得到子图的画布和坐标轴类
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    plt.plot(x, y, color='green', # marker='o',
                  linestyle='dashed',
                linewidth=2, markersize=12)
    plt.show()

如果有能力可以自己去分析一下源码

Returns  *************plt.subplots()函数的返回值************
-------
fig : :class:`matplotlib.figure.Figure` object

ax : Axes object or array of Axes objects.

    ax can be either a single :class:`matplotlib.axes.Axes` object or an
    array of Axes objects if more than one subplot was created.  The
    dimensions of the resulting array can be controlled with the squeeze
    keyword, see above.
Returns   *************plt.axes()函数的返回值************
-------
axes : Axes
    The created or activated axes.

标题:如何增加注释

在这里插入图片描述

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['KaiTi']  # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
x = np.linspace(0, 2*np.pi, 1000)
plt.plot(x, np.sin(x))
plt.text(x = np.pi/2, y = 0, s = "Hello World", fontsize=15)
plt.annotate(s = "这是一个驻点", xy = (3*np.pi/2, -1), xytext = (4,0.75),
             arrowprops  = {'width':10,'headwidth':20,'headlength':70,'shrink':1, 'facecolor':'deeppink'},fontsize = 15)
plt.show()

Axes.annotate(s, xy, *args, **kwargs)
s:注释文本的内容
xy:被注释的坐标点,二维元组形如(x,y)
xytext:注释文本的坐标点,也是二维元组,默认与xy相同
xycoords:被注释点的坐标系属性,允许输入的值如下
arrowprops:箭头的样式,dict(字典)型数据
关键字 说明
width 箭头的宽度(单位是点)
headwidth 箭头头部的宽度(点)
headlength 箭头头部的长度(点)
shrink 箭头两端收缩的百分比(占总长)

plt.text(x, y, s) x, y 是文字的位置横纵坐标s是字符串的内容

----------------------------------------------------EDN-------------------------------------------------

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值