mofanpy-Matplotlib画图教程(一):基本使用

Matplotlib官网:https://matplotlib.org/

Matplotlib基本使用

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
y = 2*x + 1
# y = x**2
plt.plot(x, y)
plt.show()

在这里插入图片描述

  • np.linspace:定义x的范围是(-1, 1),个数为50。
  • 作图三部曲
    • plt.figure(): 定义一个图像窗口
    • plt.plot(x,y): 画图
    • plt.show(): 显示

1. figure图像

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure(num=3, figsize=(8, 5),)
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.show()

在这里插入图片描述

  • plt.figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, clear, …):
    • num:编号;
    • figsize:窗口大小,(float, float)
    • dpi:分辨率
    • facecolor:背景颜色,default值是’white’
    • edgecolor:边框颜色,default值是’white’
    • frameon:bool型,是否绘制边框,default值是’True’
    • FigureClass:选择自定义的图实例
    • clear:bool型,是否清除图,default值是’False’
  • plt.plot(x, y1, color=‘red’, linewidth=1.0, linestyle=’–’):
    • x,y1是两个数列,如果是直线还可以写成[x0,y0],[x1,y1]直线的两个坐标
    • color:颜色;
    • linewidth:线宽,float型;
    • linestyle:线的类型,’–'为虚线. '-‘为实线,’-.‘为虚点线,’:'为点线

tips : 关于颜色:
(1)可以使用全称:‘green’、‘white’…
(2)可以用颜色值:#008000
(3)可以用单个字母简写:
在这里插入图片描述

2. 设置坐标

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')

在这里插入图片描述

  • 设置坐标的方法:
    plt.xlim((-1, 2))、plt.ylim((-2, 3)):设置x,y坐标的范围
    plt.xlabel(‘I am x’)、 plt.ylabel(‘I am y’):设置坐标名称
# set new ticks
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           ['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])
# to use '$ $' for math text and nice looking, e.g. '$\pi$'

在这里插入图片描述

  • 设置轴刻度
    方法一,均分数值刻度:plt.xticks( np.linspace(-1, 2, 5))
    方法二,非均分名字刻度:plt.yticks([-2, -1.8, -1, 1.22, 3], [r’$ 名称 $ ‘, r’ $ 名称 $ ‘, r’ $ normal $ ‘, r’ $ 名称 $ ‘, r’ $ 名称 $ '])
# gca = 'get current axis'
ax = plt.gca()
ax.spines['right'].set_color('green')
ax.spines['top'].set_color('blue')

在这里插入图片描述

  • 调整边框颜色:
    plt.gca:获取当前坐标轴信息;
    plt.gca.spines[ ]:设置边框:所有位置:right,left,top,bottom,both,default,none);
    plt.gca.spines[ ].set_color:设置边框颜色:默认白色; 使用.spines设置边框。
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()

在这里插入图片描述

  • 调整坐标轴
    .xaxis.set_ticks_position:设置x坐标刻度数字或名称的位置:op,bottom,both,default,none.
    .spines.set_position:设置边框位置:y=0的位置;(位置所有属性:outward,axes,data)
    • axes: percentage of y axis
    • data: depend on y data

3. Legend图例

matplotlib 中的 legend 图例就是为了帮我们展示出每个数据对应的图像名称. 更好的让读者认识到你的数据结构.(右上角显示哪条线对应的是哪个数据)

  • 自动添加图例:plt.legend(loc=‘upper right’)
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
#---------------------------以下是新内容-----------------------------------#
# set line syles
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
# 自动添加图例
plt.legend(loc='upper right')
plt.show()

在这里插入图片描述

tips:需要注意的是 l1, l2,要以逗号结尾, 因为plt.plot() 返回的是一个列表.

  • 手动添加图例:plt.legend(handles=[l1, l2], labels=[‘up’, ‘down’], loc=‘best’)
# 手动添加图例(可修改属性值)
plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='best')
# the "," is very important in here l1, = plt... and l2, = plt... for this step

在这里插入图片描述

tips
(1)如果以上面这种形式添加 legend, 我们需要确保, 在上面的代码 plt.plot(x, y2, label=‘linear line’) 和 plt.plot(x, y1, label=‘square line’) 中有用变量 l1 和 l2 分别存储起来.
(2) loc参数有如下:
best:表示自动分配最佳位置,除此之外还有upper right 、upper left 、lower left 、 lower right、right、center left、center right、lower center 、upper center、 center

4. Annotation标注

当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法, 一种是用 plt 里面的 annotate,一种是直接用 plt 里面的 text 来写标注.

import matplotlib.pyplot as plt
import numpy as np

# 绘制一根直线
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)

# 移动坐标
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

#--------------------------以下是新内容:添加标注-----------------------#
#用常规方法画出辅助线
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')

# 对这个点添加注释
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))

# 添加注释text
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

在这里插入图片描述

  • 画点的方法plt.scatter()
    .scatter(x, y, s, c, marker,alpha, linewidths, edgecolors,…)
    • x,y 数据的位置
    • s 点的大小,默认为2
    • c 点的颜色
    • marker 标记样式,默认为0
  • 添加注释
    • 方法一:plt.annotate()
      .annotate(text, xy, *args, …)

      • text 注释文本
      • xy 要注释的点 例如(x0,y0)
      • xytext 放置文本的位置
      • xycoords 坐标系统,默认是data,是说基于数据的值来选位置
      • textcoords 位置的偏移值
      • arrowprops 用于在 xy 和 xytext 之间绘制 FancyArrowPatch 箭头的属性。dict, optional Dict 可选,其中arrowstyle(箭头属性)有这样几种:
        [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EeMOYFWw-1610451213740)(attachment:image.png)]
      • annotation_clip bool值,当注记点 xy 位于轴线区域外时是否裁剪绘制注记。
    • 方法二:plt.text()
      .text(x, y, s, fontdict, …)

      • xy 注释的位置
      • s 注释的文本
      • fontdict 文本属性
  • r’$$'格式
    • r’$ 2x+1=%s$’%y0 y0替代了中间的%s
    • r’$ This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$’
      空格需要用到转字符\,注意带角标的罗马字母要如何写

5. tick 能见度

当图片中的内容较多,相互遮盖时,我们可以通过设置相关内容的透明度来使图片更易于观察。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure()
plt.plot(x, y, linewidth=10, zorder=1)      # set zorder for ordering the plot in plt 2.0.2 or higher
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

#------------------------------------以下是新内容----------------------------------#
#对被遮挡的图像调节相关透明度
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.8, zorder=2))
plt.show()

在这里插入图片描述

其中label.set_fontsize(12)重新调节字体大小,bbox设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值