Matplotlib之绘图示例

1. 线图(line plot)

plot()

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt, subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='About as simple as it gets, folks') # 设置x,y轴标签和图形标题
ax.grid() # 开启网格

fig.savefig("test.png") # 保存图片
plt.show()

线图

多子图(Multiple subplots)

subplot()

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1) # 等价于plt.subplot(211)
plt.plot(x1, y1, 'o-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 1, 2) # 等价于plt.subplot(212)
plt.plot(x2, y2, '.-')
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()

多子图

2. 图片(Images)

imshow()

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
from matplotlib.path import Path
from matplotlib.patches import PathPatch

# 加载上面保存的test.png图片
with cbook.get_sample_data(r'C:\Users\sjl\my_jupyter_notebook\my_matplotlib\test.png') as image_file:
	image = plt.imread(image_file)

fig, ax = plt.subplots()
ax.imshow(image)
ax.axis('off') # 清除x-axis和y-axis

# w, h = 512, 512

# with cbook.get_sample_data('ct.raw.gz') as datafile:
# 	s = datafile.read()
# A = np.frombuffer(s, np.uint16).astype(float).reshape(w, h))
# A /= A.max()
# 
# fig, ax = plt.subplots()
# extent = (0, 25, 0, 25)
# im = ax.imshow(A, cmap=plt.cm.hot, origin='upper', # extent=extent)
# 
# markers = [(15.9, 14.5), (16.8, 15)]
# x, y = zip(*markers)
# ax.plot(x, y, 'o')
# 
# ax.set_title('CT density')

plt.show()

加载图片

3. 轮廓和伪色(Contouring and pseudocolor)

pcolormesh()contour()

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import numpy as np

dx, dy = 0.05, 0.05

y, x = np.mgrid[slice(1, 5 + dy, dy), slice(1, 5 + dx, dx)]

z = np.sin(x) ** 10 + np.cos(10 + y*x) * np.cos(x)

z = z[:-1, :-1]
levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max()) # 刻度的最大间隔数量为15,刻度的上下限位z.min()和z.max()

cmap = plt.get_cmap('PiYG')
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True) # 根据离散间隔生成颜色图索引

fig, (ax0, ax1) = plt.subplots(nrows=2)

im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm)
fig.colorbar(im, ax=ax0)
ax0.set_title('pcolormesh with levels')

cf = ax1.contour(x[:-1, :-1] + dx/2., y[:-1, :-1] + dy/2., z, levels=levels, cmap=cmap)

fig.colorbar(cf, ax=ax1)
ax1.set_title('contour with levels')
fig.tight_layout()

plt.show()

轮廓和伪色

4. 直方图(Histograms)

import matplotlib
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(19680801)

mu = 100 # 分布的均值
sigma = 15 # 分布的标准差
x = mu + sigma * np.random.randn(437)
num_bins = 50

fig, ax = plt.subplots()

n, bins, patches = ax.hist(x, num_bins, density=1) # 直方图的数据

# 添加一条拟合线
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 /sigma * (bins - mu)) ** 2))

ax.plot(bins, y, '--')
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability density')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

fig.tight_layout() # 调整间距以防止截断ylabel
plt.show()

在这里插入图片描述

5. 路径图(Path)

import matplotlib.path as mpath # matplotlib中处理折线的模块
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

Path = mpath.Path
path_data = [
	(Path.MOVETO, (1.58, -2.57)), # (顶点类型,顶点坐标)
    (Path.CURVE4, (0.35, -1.1)),
    (Path.CURVE4, (-1.75, 2.0)),
    (Path.CURVE4, (0.375, 2.0)),
    (Path.LINETO, (0.85, 1.15)),
    (Path.CURVE4, (2.2, 3.2)),
    (Path.CURVE4, (3, 0.05)),
    (Path.CURVE4, (2.0, -0.5)),
    (Path.CLOSEPOLY, (1.58, -2.57)),	
]
codes, verts = zip(*path_data) # 定点类型, 顶点
path = mpath.Path(verts, codes) # 创建路径
patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
ax.add_patch(patch)

x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')

ax.grid()
ax.axis('equal')
plt.show()

路径图

6. 3D表面(颜色图)(3D surface (color map))

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np


fig = plt.figure()
ax = fig.gca(projection='3d')

# 造数据
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2, Y**2)
Z = np.sin(R)

# 绘制surface
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

# 自定义z轴
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# 添加颜色条
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是三个关于Matplotlib绘图的代码示例示例1:绘制线形图 ```python import numpy as np import matplotlib.pyplot as plt x = np.linspace(-2, 2, 100) y = x**2 z = np.sqrt(4-x**2) plt.plot(x, y, label='$y=x^2$', color='red', linewidth=2) plt.plot(x, z, 'b--', label='$x^2 + y^2 = 4$') plt.plot(x, -z, 'y--', label='$x^2 + y^2 = 4$') plt.xlabel('x轴') plt.ylabel('y轴') plt.title('线形图') plt.xlim(-5, 5) plt.ylim(-5, 5) plt.legend() plt.grid() plt.savefig('pyplot.png', format='png', dpi=500) plt.show() ``` 示例2:绘制带箭头的坐标轴 ```python import matplotlib.pyplot as plt import mpl_toolkits.axisartist as axisartist import numpy as np fig = plt.figure(figsize=(6, 6)) ax = axisartist.Subplot(fig, 111) fig.add_axes(ax) ax.axis[:].set_visible(False) ax.axis['x'] = ax.new_floating_axis(0, 0) ax.axis['y'] = ax.new_floating_axis(1, 0) ax.axis['x'].set_axisline_style('-|>', size=1.0) ax.axis['y'].set_axisline_style('-|>', size=1.0) ax.axis['x'].set_axis_direction('top') ax.axis['y'].set_axis_direction('right') plt.xlim(-10, 10) plt.ylim(-0.1, 1.2) x = np.arange(-10, 10, 0.1) y = 1/(1 + np.exp(-x)) plt.plot(x, y, label=r'$sigmoid=\frac{1}{1+e^{-x}}$', c='r') plt.legend() plt.savefig('sigmoid.png', format='png', dpi=500) plt.show() ``` 示例3:添加图例说明 ```python import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [10, 20, 25, 30], label='Philadelphia') ax.plot([1, 2, 3, 4], [30, 23, 13, 4], label='Boston') ax.scatter([1, 2, 3, 4], [20, 10, 30, 15], label='Point') ax.set(ylabel='Temperature (deg C)', xlabel='Time', title='A tale of two cities') ax.legend() plt.show() ``` 这些示例展示了Matplotlib绘图的不同用法,包括绘制线形图、带箭头的坐标轴和添加图例说明。你可以根据需要选择适合的示例进行使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值