Matplotlib 使用笔记(一)——基本用法

1、基础用法

plt.plot(x, y,color=' ', linewidth=1.0, linestyle=' ')
plt.show()

2、figure

plt.figure(num=2, figuresize = (3,9))
plt.plot(x,y)
#一张图内可绘制多个曲线
plt.show()

3、设置坐标轴

    #坐标轴取值范围
    plt.xlim()
    plt.ylim()
    #坐标轴名称
    plt.xlabel()
    plt.ylabel()
    #修改坐标刻度
    plt.xticks()
    plt.yticks()          Eg: plt.yticks([-2,-1.8,-1,1.22,3],
                                         ['really bad', 'bad', 'normal', 'good', 'really good'])  #修改刻度及名称
                                         //修改字体[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']      \ 转字符    \\alpha---> α

    ###gac= 'get current axis'   获取当前坐标轴信息
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')    #设置x坐标刻度数字或名称的位置
    ax.yaxis.set_ticks_position('left')
    ax.spines['bottom'].set_position(('data',0))    #设置边框及位置 
    ax.spines['left'].set_position(('data',0))

.spines设置边框
.set_position设置边框位置
所有位置: top, bottom, both, default, none
位置所有属性:outwardaxes(百分比),data(具体数字)

Code:

    import matplotlib.pyplot as plt
    import  numpy as np

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

    plt.figure()
    plt.plot(x,y1)
    plt.plot(x,y2, color = 'red', linewidth = 1.0, linestyle = '--')
    plt.xlim((-1,2))
    plt.ylim((-2,3))

    new_ticks = np.linspace(-1,2,5)
    plt.xticks(new_ticks)
    plt.yticks([-2,-1.8,-1,1.22,3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$',])

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

    plt.show()

这里写图片描述

4、legend 图例

第一种:

    plt.plot(x,y1, label = 'linear line')
    plt.plot(x,y2,color = 'red', linewidth = 1.0, linestyle = '--',label = 'triple line')
    plt.legend()

第二种:

    l1, = plt.plot(x,y1, label = 'linear line')   #用变量存储,注意以逗号结尾
    l2, =plt.plot(x,y2, color = 'red', linewidth = 1.0, linestyle = '--',label = 'triple line')
    plt.legend(loc = 'upper right')
  或 plt.legend(handles = [l1,l2], labels = ['up', 'down'], loc = 'best')

loc 参数:'best', 'upper right','upper left', 'lower left','lower right', 'right','center left', 'center right', 'lower center', 'upper center','center'
这里写图片描述

5、Annotation 标注

第一种:.annotate

"""method 1"""
######################################
x0=2
y0=x0**3
plt.scatter(x0, y0, s=50, color = 'b')                 #设置散点
plt.plot([x0,x0],[0,y0], 'k--', linewidth = 2.5)       #绘制虚线
plt.annotate(r'$x^3=%s$'%y0,                           #标注内容
                     xy=(x0,y0),                       #标注点
                     xycoords = 'data',                #基于数据的值来选位置
                     xytext = (+30,-30),
                     textcoords = 'offset points',     #标注位置
                     fontsize = 16,
                     arrowprops = dict(arrowstyle ='->', connectionstyle = "arc3, rad = .2"))         #对标注箭头的设置

第二种:.text

"""method 2"""
########################################
plt.text(-3,10,                                     #标注位置
         r'$This\ is\ an\ example.$',               #标注内容
         fontdict = {'size':16, 'color':'g'})       #设置文本

这里写图片描述

6、tick能见度

for label in ax.get_xticklabels()+ax.get_yticklabels():
    label.set_fontsize(12)                         #重新调节字体大小
    label.set_bbox(dict(facecolor = 'white',       #调节box前景色
                         edgecolor = 'None',       #设置边框
                        alpha = 0.7,               #alpha设置透明度
                        zorder = 2)

这里写图片描述

2018.08.05 整理于莫烦Python教学视频

https://morvanzhou.github.io/tutorials/data-manipulation/plt/2-1-basic-usage/

### Matplotlib 中 Figure 和 Axes 的详细用法及区别 #### 、Figure 定义与创建 在 Matplotlib 中,`Figure` 是指整个图像窗口或者画布,可以包含个或多个轴(Axes)。通过 `plt.figure()` 函数来创建个新的 Figure 对象。可以通过传递参数来自定义其大小和其他属性。 ```python import matplotlib.pyplot as plt fig = plt.figure(figsize=(8, 6)) # 创建个指定尺寸的新 figure ``` #### 二、Axes 定义及其特性 `Axes` 表示的是图表中的个特定绘图区域[^1]。不要将其与数学上的坐标轴混淆。每个 Axes 都拥有独立的坐标系统、刻度以及标签等组件,并且几乎所有的图形元素都隶属于某个 Axes 实例之下,比如线条、文本框或是图例等等。 为了向现有的 Figure 添加新的 Axes 可以使用如下几种方式之: - 使用 `add_subplot()` 方法快速添加标准布局下的子图; - 利用更灵活的 `subplot2grid()` 来精确控制位置和跨越范围; - 或者直接调用 `add_axes()` 手动设置矩形边界内的新 Axes[^3]。 下面是个简单的例子展示如何利用 add_axes() 方法自定义添加 Axes: ```python from matplotlib import pyplot as plt import numpy as np import math x = np.arange(0, math.pi * 2, 0.05) y = np.sin(x) fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) ax.plot(x, y) plt.show() ``` #### 三、两者之间的关系 通常情况下,在同个 Figure 上会存在至少对 Axes;而当涉及到多面板或多子图的情况时,则会在同张 Figure 下面挂载多个不同的 Axes 实例。因此可以说 Figures 提供了个容器用来容纳并管理这些 Axes 子部件们。 #### 四、常用操作 对于 Axes 而言,经常使用的功能包括但不限于调整边距 (`set_margins`)、修改背景颜色(`set_facecolor`)、隐藏/显示网格线(grid),还有最重要的就是绘制数据点了——这正是 Axes.plot() 接口所负责的工作[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值