Matplotlib基础

本文详细介绍了Python的Matplotlib库,包括基础用法、Figure对象、坐标轴设置、图例、标注、散点图、直方图和等高线图的绘制。通过实例展示了如何创建和定制图形,如设置坐标轴范围、颜色、线条样式、图例和注释,并提供了多个实用函数的使用方法。
摘要由CSDN通过智能技术生成

Matplotlib

Matplotlib 是Python中类似 MATLAB 的绘图工具,熟悉 MATLAB 也可以很快的上手 Matplotlib。

1.Matplotlib基础用法

plot是绘制各种图形的命令子库,相当于快捷方式。
plt.plot(x,y,format_string,**kwargs)常用参数意义:

  1. x:横坐标
  2. y:纵坐标
  3. format_string:定义线条的颜色和样式的操作
  4. linestyle:线条风格
  5. linewidth:线条宽度
  6. alpha:透明度
  7. color:线段颜色
def matplotlib_1():
    """
    matplotlib 最基本的用法
    :return:  在平面直角坐标系中画出图像
    """
    x = np.linspace(-10, 10, 10000)
    y = np.sin(x)
    plt.plot(x, y)
    plt.show()  # 显示出图像。

注意在pycharm中运行一定要有plt.show(),不然不会显示图像。
运行结果:
在这里插入图片描述

2.Matplotlib中Figure

在任何绘图之前,我们需要一个Figure对象,可以理解成我们需要一张画板才能开始绘图。

def matplotlib_figure():
    """
    我的理解是一个figure对应一个框框,
    如果要两个图像显示在两个框框中就在每一个前面都写一个figure
    如果不需要则在两个前面写一个figure就可以了
    :return: 画出图像
    """
    x = np.linspace(-1, 1, 100)
    y1 = 2 * x + 1
    y2 = x ** 2

    # 图像显示在两个figure中
    plt.figure()
    plt.plot(x, y1)
    plt.figure()
    plt.plot(x, y2)

    # 将图像显示在一个figure中
    plt.figure(figsize=(5, 5))
    plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
    plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')

    plt.show()

运行结果:
两张图分开。
x,y1
x,y2
两张图放在一起:
在这里插入图片描述

3.Matplotlib设置坐标轴

  1. plt.xlim()、plt.yli接收元组数据设置坐标轴范围。
  2. plt.xlabel,plt.ylabel:接收字符串对文本信息进行描述。
  3. plt.xticks(ticks=None, labels=None, **kwargs)、plt.yticks。ticks:应当放置刻度的位置列表。labels:在给定位置放置的标签。
  4. plt.gca():进行坐标轴的移动。
  5. spines:接收位置
  6. set_color:设置颜色
  7. set_position设置位置
def matplotlib_3():
    """
    设置坐标轴
    :return:
    """
    x = np.linspace(-1, 1, 100)
    y1 = 2 * x + 1
    y2 = x ** 2
    # 限制x, y 的坐标范围
    plt.xlim((-1, 1))
    plt.ylim((-1, 2))
    # 对横纵坐标进行描述
    plt.xlabel("I am X")
    plt.ylabel("I am Y")
    plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
    plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')
    # 新的横坐标
    new_ticks = np.linspace(-2, 2, 10)
    plt.xticks(new_ticks)
    plt.yticks([-1, 0, 1, 2, 3],
               ['lavel1', 'lavel2', 'lavel3', 'lavel4', 'lavel5'])
    # gca get current axis
    # 利用plt.gca( )进行坐标轴的移动
    ax = plt.gca()
    # 设置边框颜色
    ax.spines['right'].set_color('red')
    ax.spines['top'].set_color('green')
    # 把X轴的刻度设置为‘bottom’
    # 把Y轴的刻度设置为‘left’
    # 设置bottom和left对应到零点位置
    ax.spines['bottom'].set_position(('data', 0))
    ax.spines['left'].set_position(('data', 0))
    plt.show()

在这里插入图片描述

4.Matplotlib设置标签

一个Figure中有多条线时不仅可以设置颜色不同,还可以设置标签来标注线段的含义。
plt.legend(*args, **kwargs)

  1. handles:接收列表代表要标注的线段。
  2. labels:接收列表和代表和handles一一对应的标签。
  3. loc:标签设置的位置
def matplotlib_4():
    """
    设置图例
    :return:显示图像
    """
    x = np.linspace(-1, 1, 100)
    y1 = 2 * x + 1
    y2 = x ** 2
    # 限制x, y 的坐标范围
    plt.xlim((-1, 1))
    plt.ylim((-1, 2))
    # 对横纵坐标进行描述
    plt.xlabel("I am X")
    plt.ylabel("I am Y")
    l1, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
    l2, = plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')
    # 设置图例
    plt.legend(handles=[l1, l2], labels=['test1', 'test2'], loc='best')
    """
    handles = [],中间放线,
    labels = [],中间放标签名称
    loc = 'best', 系统自动找最合适的位置来放置标签
    """
    # 新的横坐标
    new_ticks = np.linspace(-1, 1, 10)
    plt.xticks(new_ticks)
    plt.yticks([-1, 0, 1, 2, 3],
               ['lavel1', 'lavel2', 'lavel3', 'lavel4', 'lavel5'])
    plt.show()

在这里插入图片描述

5.Matplotlib设置标注

plt.annotate(text, xy, *args, **kwargs)

  1. text:注释文本内容
  2. xy:被指向的数据点(x,y)的位置坐标
  3. xytext:文字相对于所要标注的点所在的位置
  4. textcoords :注释文本的坐标系属性(‘offset points’以点为单位偏移。‘offset pixels’以像素为单位偏移)
  5. arrowprops:箭头的样式,dict(字典)型数据。(arrowstyle:箭头风格。connectionstyle设置箭头样式和弯曲度)

plt.text(x, y, s, fontdict=None, withdash=False, **kwargs)

  1. x,y:显示内容的坐标位置
  2. s:显示内容
  3. fontdict:一个定义s格式的dict
def matplotlib_5():
    x = np.linspace(-1, 1, 100)
    y1 = 2 * x + 1
    y2 = x ** 2
    # 限制x, y 的坐标范围
    plt.xlim((-1, 1))
    plt.ylim((-1, 2))
    # 对横纵坐标进行描述
    plt.xlabel("I am X")
    plt.ylabel("I am Y")
    plt.plot(x, y1, color='red', linewidth=2.0, linestyle='--')
    plt.plot(x, y2, color='green', linewidth=2.0, linestyle='-.')
    # 新的横坐标
    new_ticks = np.linspace(-2, 2, 10)
    plt.yticks([-1, 0, 1, 2, 3],
               ['lavel1', 'lavel2', 'lavel3', 'lavel4', 'lavel5'])
    # gca get current axis
    # 利用plt.gca( )进行坐标轴的移动
    ax = plt.gca()
    # 设置边框颜色
    ax.spines['right'].set_color('red')
    ax.spines['top'].set_color('green')
    # 把X轴的刻度设置为‘bottom’
    # 把Y轴的刻度设置为‘left’
    # 设置bottom和left对应到零点位置
    ax.spines['bottom'].set_position(('data', 0))
    ax.spines['left'].set_position(('data', 0))

    x0 = 0.5
    y0 = 2 * x0 + 1

    # 画点
    plt.scatter(x0, y0, s=50, color='blue')  # s是大小

    # 画虚线
    plt.plot([x0, x0], [y0, 0], color='black', linewidth=2.0, linestyle='-') # x0, y0 代表蓝色点,x0,0代表X轴上的点。

    plt.annotate(f'2x+1={y0}', xy=(x0, y0), xytext=(+30, -30), textcoords='offset points', fontsize=16,
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'), weight='heavy')
    """
    xy代表所指向的点坐标
    xytest代表文字描述相对于所指向的点坐标所处的位置
    """

    plt.text(-1, 2, 'this is the text', fontdict={'size':'16', 'color':'red'})
    plt.show()

在这里插入图片描述

6.Matplotlib散点图

plt.scatter

  1. x、y:点坐标
  2. color:点颜色
  3. alpha:透明度
def matplotlib_6():
    x = np.random.normal(0, 1, 1500)
    y = np.random.normal(0, 1, 1500) # 0-1的正态分布
    plt.scatter(x, y, color='red', alpha=0.5) # alpha代表透明度
    plt.show()

在这里插入图片描述

7.Matplotlib直方图

plt.bar():画直方图

def matplotlib_7():
    x = np.arange(10)
    y = 2**x + 10
    plt.bar(x, y, color='b')
    for x,y in zip(x, y): # 将x,y结合成一个整体
        plt.text(x+0.4,y,f'{y}',va='bottom', ha='center')
    plt.show()

在这里插入图片描述

8.Matplotlib等高线

coutour([X, Y,] Z,[levels], **kwargs)

  1. X,Y类似横纵坐标
  2. Z:类似矩阵绘制轮廓的高度值
  3. 代码中,8代表八条线
  4. cmap代表等高线颜色样式
def f(x, y):
    return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)

def matplotlib_8():
    x = np.linspace(-3, 3, 100)
    y = np.linspace(-3, 3, 100)
    X, Y = np.meshgrid(x, y)
    plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
    plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值