Matplotlib 是一个强大的绘图库,常用于数据可视化。本文将介绍如何调整 Matplotlib 的布局,使其更美观、更易于阅读。
布局简介
Matplotlib 的布局是指图形的排列方式,包括子图(subplots)的排列、标题、标签等元素的布局。
调整布局
1. 使用 subplots_adjust
subplots_adjust
函数可以调整子图之间的间距。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
fig.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1)
plt.show()
2. 使用 GridSpec
GridSpec
可以创建更复杂的布局。
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
fig = plt.figure()
gs = gridspec.GridSpec(2, 2, height_ratios=[1, 2], width_ratios=[2, 1])
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1])
ax3 = fig.add_subplot(gs[1, :])
ax1.plot([1, 2, 3], [1, 4, 9])
ax2.bar([1, 2, 3], [1, 4, 9])
ax3.scatter([1, 2, 3], [1, 4, 9])
plt.show()
图例位置调整
有时候,图例的位置可能会挡住图形的一部分。可以使用 legend
函数的 loc
参数来调整图例的位置。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9], label='Line')
ax.scatter([1, 2, 3], [1, 4, 9], label='Scatter')
ax.legend(loc='upper left')
plt.show()
扩展阅读
想要了解更多关于 Matplotlib 的内容,可以访问我们的 Matplotlib 教程。
matplotlib