matplotlib作图方法

本文详细介绍了使用Python的Matplotlib库进行数据可视化的方法,包括基本的线性图表绘制、正弦曲线、余弦曲线的子图展示,以及如何调整图表样式、颜色和线条类型。此外,还讲解了如何创建3D表面图,并提供了调整坐标轴范围和制作柱状图的技巧。

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

Matplotlib python作图


导入需要的包numpy和matpl

import numpy as np
import matplotlib.pyplot as plt

作图实例

x=np.arange(1,10)      #x=array([1, 2, 3, 4, 5, 6, 7, 8, 9])
y=3*x+5                #y=array([ 8, 11, 14, 17, 20, 23, 26, 29, 32])
plt.plot(x,y)          #[<matplotlib.lines.Line2D object at 0x000001E4B9CB3AC8>]
plt.show()

y=3x+5的函数图
[−π,π][-\pi,\pi][π,π]上y=sinx的图

x=np.arange(-np.pi,np.pi+0.01,0.01)
y=np.sin(x)
plt.plot(x,y)
plt.show()

y=sinx,x∈[-\pi,\pi]

plt.title("     ")     #改变标题
plt.xlabel("     "     #改变x轴名称
plt.ylabel("    ")     #改变y轴名称

在plt.plot()中添加不同的格式字符能达到不同的显示效果

字符效果
“-”实线
“–”虚线
“-.”点划线
“g”绿色
“r”红色
#颜色用plt.plot(color="   ")
#虚线或实现用plt.plot(linestyle="   ")
#要在同一张图中作两张子图,需要plt.subplot()
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-3*np.pi,3*np.pi,0.1)
y1=np.cos(x)
y2=np.sin(x)
plt.subplot(2,2,1) #高为2,宽为1,第1张图
plt.plot(x,y1)
plt.subplot(2,2,2) #高为2,宽为1,第2张图
plt.plot(x,y2)
plt.show()

在这里插入图片描述

#同时作出两张图,需要在代码中添加 plt.figure()
x=np.arange(1,10)
y1=3*x
y2=np.sin(x)
plt.figure()
plt.plot(x,y1)

plt.figure()
plt.plot(x,y2)
plt.show()
#plt.figure("   ")中可填入figure名称
#figure(figsize=(a,b))可调整大小

在这里插入图片描述

设置坐标轴

plt.xlim((left,right)) #给出范围
plt.xlim(left=3)   #只给出左边的界限
plt.xlim(right=10) #只给出右边的界限

柱状图

plt.bar(x,y)

3D图

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig=plt.figure()
ax=Axes3D(fig)
X=np.arange(-4,4,0.25)
Y=np.arange(-4,4,0.25)
X,Y=np.meshgrid(X,Y) #将两个一维数组变成二维数组
>>> X
array([[-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       ...,
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95],
       [-4.  , -3.95, -3.9 , ...,  3.85,  3.9 ,  3.95]])
>>> Y
array([[-4.  , -4.  , -4.  , ..., -4.  , -4.  , -4.  ],
       [-3.95, -3.95, -3.95, ..., -3.95, -3.95, -3.95],
       [-3.9 , -3.9 , -3.9 , ..., -3.9 , -3.9 , -3.9 ],
       ...,
       [ 3.85,  3.85,  3.85, ...,  3.85,  3.85,  3.85],
       [ 3.9 ,  3.9 ,  3.9 , ...,  3.9 ,  3.9 ,  3.9 ],
       [ 3.95,  3.95,  3.95, ...,  3.95,  3.95,  3.95]])


R=np.sqrt(X*X+Y*Y)
Z=np.sin(R)
ax.plot_surface(X,Y,Z,cmap=plt.get_cmap('rainbow'))
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值