Matplotlib

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
plt.style.use(['science', 'notebook', 'no-latex'])

注意,使用 jupyter notebook 时,在每个单元格运行后,图表被重置,因此对于更复杂的图表,你必须将所有绘图命令放在单个 notebook 单元格中

Matplotlib 风格


install

pip install SciencePlots

Using the Styles

# Science Plots 中包含的更多 styles 可以参考 github repo
plt.style.use(['science', 'notebook', 'no-latex'])

Check available styles

print(plt.style.available)

Matplotlib 基础操作

图片与子图

  • matplotlib 所绘制的图位于图片 (Figure) 对象中,可以用 plt.figure() 生成一个新的图片。当然,我们也不能用空白的图片进行绘图,需要用 Figure 对象的 add_subplot 方法创建一个或多个子图 (subplot)fig.add_subplot 返回 AxesSubplot 对象,可以使用这些对象的实例方法进行绘图
fig = plt.figure(figsize=(10, 8), dpi=100)  # figsize=(width, height), dpi means resolution

ax1 = fig.add_subplot(2, 2, 1)  # create 2x2 subplots and use the first one
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)

ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))

fig.tight_layout()
plt.show()

在这里插入图片描述

  • matplotlib 还包含了一个创建子图的便捷方法 plt.subplots,它创建一个新的图片,然后返回图片以及包含了已生成子图对象的 Numpy 数组
fig, axes = plt.subplots(2, 2)

axes[0, 0].hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
axes[0, 1].scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))

fig.tight_layout()
plt.show()
  • 如果不显式创建图像和子图而是直接使用 plt.plot,则默认会在最后一个图片的最后一个子图上进行绘制,从而隐藏图片和子图的创建

绘图属性 (颜色、线类型、标签、标题、刻度、图例)

  • plt.xlim, plt.xticks, plt.xticklabels 分别控制了绘图范围刻度位置以及刻度标签。可以在两种方式中使用:
plt.xlim, plt.xticks, plt.xticklabels
1. 在没有函数参数传入时,返回当前的参数值 (如 plt.xlim() 返回当前的 x x x 轴绘图范围)
2. 传入函数参数时用于设置参数值 (如 plt.xlim([0, 10]) 设置 x x x 轴范围为 0 ~ 10)
  • 上述方法都会在当前活动的或最近创建的 AxesSubplot 上生效。这些方法中的每一个都对应于子图自身的两个方法。如 plt.xlim 对应于 ax.get_xlimax.set_xlim。使用 subplot 实例方法可以更为显式地进行设置
fig = plt.figure(figsize=(5, 4), dpi=100)
ax1 = fig.add_subplot(1, 1, 1)

x = np.arange(0, 6, 0.1)
ax1.plot(x, np.sin(x), 'g--' , label='sin')
ax1.plot(x, np.cos(x), 'r--' , label='cos')

ax1.set_ylim([-1, 1])       # set range of y ticks
ax1.set_xticks([0, 3, 6])   # set x ticks
ax1.set_xticklabels(['zero', 'three', 'six'], rotation=30)  # set labels of x ticks
ax1.tick_params(axis="x", labelsize=18)
ax1.set_xlabel('x')         # set labels
ax1.set_ylabel('y')
ax1.set_title('sin & cos')	# set title
ax1.legend(loc='best')      # set legend

fig.tight_layout()
plt.show()

在这里插入图片描述

  • 轴的类型还有一个 set 方法,允许批量设置绘图属性
fig = plt.figure(figsize=(5, 4), dpi=100)
ax1 = fig.add_subplot(1, 1, 1)

x = np.arange(0, 6, 0.1)
ax1.plot(x, np.sin(x), 'g--' , label='sin')
ax1.plot(x, np.cos(x), 'r--' , label='cos')

props = {
    'ylim': [-1, 1],        # set range of y ticks
    'xticks': [0, 3, 6],    # set x ticks
    'xticklabels': ['zero', 'three', 'six'],    # set labels of x ticks
    'xlabel': 'x',          # set labels
    'ylabel': 'y',
    'title': 'sin & cos'    # set title
}
    
ax1.set(**props)
ax1.legend(loc='best')      # set legend

fig.tight_layout()
plt.show()
  • 通常可以设置这些绘图属性使得作图更加美观,e.g. linewidth=2, linestyle=“–”, color=“red”, marker=“o”ax.grid()

将图片保存到文件

  • plt.savefig / fig.savefig. 存储的文件格式可以为 ‘svg’, ‘png’, ‘pdf’, ‘ps’, ‘eps’ …
savefig 选项描述
dpi每英寸点数的分辨率,默认为 100
bbox_inches要保存的图片范围,如果传递 ‘tight’,将会去除掉图片周围空白的部分
facecolor, edgecolor子图之外的图形背景的颜色,默认为 ‘w’ 白色
plt.savefig('figpath.png', dpi=4000, bbox_inches='tight')

图像读取与保存

读取图像为 Numpy 数组

img = mpimg.imread('cat.jpg') 	# 返回一个 Numpy 数组 (h, w, c)
								# 如果图片是 png 格式,则 Numpy 数组元素类型为 float32,否则为 uint8

将 Numpy 数组可视化

imgplot = plt.imshow(img)

在这里插入图片描述

参考文献

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值