最重要的一张图了,有助于了解一下图的各个组成部分。最重要的一句话就是 Figure包含至少一个Axes,每个Axes可以被认为是一个模块(包含坐标轴,标题,图像内容等)。因此,创建单图的时候就是在Figure中唯一一个axes上进行设置;多图的时候就是分别对每一个axes进行设置。
fig = plt.figure() # an empty figure with no Axes
fig, ax = plt.subplots() # a figure with a single Axes
fig, axs = plt.subplots(2, 2) # a figure with a 2x2 grid of Axes. Here axs contains two axes.
fig, (ax1, ax2) = plt.subplots(1, 2) # a figure with a 1*2 grid of Axes
|
|
其实 https://matplotlib.org/stable/users/explain/quick_start.html 中个介绍的比较清楚,但是比较长,这边就简化些。
需要用的包:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
-
基本单张图
x = np.linspace(0, 2, 100) # Sample data. plt.figure(figsize=(5, 2.7), layout='constrained') plt.plot(x, x, label='linear') # Plot some data on the (implicit) axes. plt.plot(x, x**2, label='quadratic') # etc. plt.plot(x, x**3, label='cubic') plt.xlabel('x label') plt.ylabel('y label') plt.title("Simple Plot") plt.legend() plt.show()
很简单,但是不太推荐这种形式,尤其是需要更改复杂的东西的时候。下面这种形式更加推荐。
x = np.linspace(0, 2, 100) # Sample data. # Note that even in the OO-style, we use `.pyplot.figure` to create the Figure. fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained') ax.plot(x, x, label='linear') # Plot some data on the axes. ax.plot(x, x**2, label='quadratic') # Plot more data on the axes... ax.plot(x, x**3, label='cubic') # ... and some more. ax.set_xlabel('x label') # Add an x-label to the axes. ax.set_ylabel('y label') # Add a y-label to the axes. ax.set_title("Simple Plot") # Add a title to the axes. ax.legend() # Add a legend. plt.show()
-
多图排列
import matplotlib.pyplot as plt import numpy as np # Helper function used for visualization in the following examples def identify_axes(ax_dict, fontsize=48): """ Helper to identify the Axes in the examples below. Draws the label in a large font in the center of the Axes. Parameters ---------- ax_dict : dict[str, Axes] Mapping between the title / label and the Axes. fontsize : int, optional How big the label should be. """ kw = dict(ha="center", va="center", fontsize=fontsize, color="darkgrey") for k, ax in ax_dict.items(): ax.text(0.5, 0.5, k, transform=ax.transAxes, **kw) np.random.seed(19680801) hist_data = np.random.randn(1_500) fig = plt.figure(layout="constrained") ax_array = fig.subplots(2, 2, squeeze=False) ax_array[0, 0].bar(["a", "b", "c"], [5, 7, 9]) ax_array[0, 1].plot([1, 2, 3]) ax_array[1, 0].hist(hist_data, bins="auto") ax_array[1, 1].imshow([[1, 2], [2, 1]]) identify_axes( {(j, k): a for j, r in enumerate(ax_array) for k, a in enumerate(r)}, )
ax_array = plt.figure(layout="constrained").subplot_mosaic( """ .α. b☢ℝ ddd """, empty_sentinel=".", # default # set the height ratios between the rows height_ratios=[1, 3.5, 1], # set the width ratios between the columns width_ratios=[1, 3.5, 1], per_subplot_kw={ "☢": {"projection": "polar"}, }, ) np.random.seed(19680801) hist_data = np.random.randn(1_500) ax_array['α'].bar(["a", "b", "c"], [5, 7, 9]) ax_array['b'].plot([1, 2, 3]) ax_array['d'].hist(hist_data, bins="auto") ax_array['ℝ'].imshow([[1, 2], [2, 1]]) identify_axes(ax_array)
更多请参考https://matplotlib.org/stable/users/explain/axes/mosaic.html ,花样太多了,根本用不过来。
-
保存图像
fig.savefig('MyFigure.png', dpi=300, bbox_inches='tight', pad_inches=0.2)
-
颜色color
-
marker的形式