matplotlib基本操作

本文介绍了使用matplotlib进行图形绘制的基本操作,包括绘制两条线的方程,定义figure,调整坐标轴范围,设置坐标轴描述,自定义刻度,隐藏边框,添加图例,散点图,注释以及特殊的标注方式,详细讲解了plot、legend、scatter和text等函数的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import matplotlib.pyplot as plt
import numpy as np

写出两条线的方程,x是-3到3之间50个数的等差数列

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

定义一个figure下的所有操作都属于这个figure

plt.figure()
plt.plot(x, y1)

定义第二个figure

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

效果图

对坐标轴的操作,还是上面的两条线

设置坐标轴的范围

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

增加坐标轴的描述

plt.xlabel('I am X')
plt.ylabel('I am Y')

对坐标轴的刻度进行替换

new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, 1, 3], ['really bad', 'bad', 'normal', 'nice'])

在这里插入图片描述

gca:get current axis
隐藏上面和右边的边界

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))

在这里插入图片描述
Legend图例
在plt.plot中加上label标签
而legend函数中也可以加很多参数,如loc等

plt.plot(x, y2, label='up')
plt.plot(x, y1,label='down', color='red', linewidth=1.0, linestyle='--')
plt.legend()

右下角图例

scatter代表画点,s代表size点的大小
下面用了简写,‘k–’代表黑色虚线,lw代表线的宽度

x0 = 1
y0 = 2 * x0 + 1
plt.scatter(x0, y0, s=50, color='b')
plt.plot([x0, x0], [y0, 0], 'k--',lw =2.5)

黑色的那条线
增加annotation
2x+1=3-----------------内容
xy=(x0, y0), xycoords=‘data’------------------以x0,y0为起点
xytext=(+30, -30),textcoords=‘offset points’-------------------text平移
arrowprops=dict(arrowstyle=’->’, connectionstyle=‘arc3,rad=.2’)---------设置那条弧线

plt.annotate('2x+1=3',xy=(x0, y0), xycoords='data', xytext=(+30, -30),textcoords='offset points',
             fontsize=16,arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))

在这里插入图片描述
另一种标注
仔细看text的格式,如何写一些特殊符号,空格

plt.text(-5.7, 6, r'$This\ is\ some\ text\ \mu\ \sigma_i\ \alpha_t$', fontdict={'size':16, 'color':'b'})

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值