当先锋百科网

首页 1 2 3 4 5 6 7
  • 本文系统梳理了Matplotlib教程

 

博文速览

本文篇幅长【1.4W+字】,如果时间紧张,建议只看标有star的部分。

 

star一、Matplotlib使用Tips

Matplotlib获取帮助途径

绘图十规则

常见绘图设置问题

二、图形快速绘制

star1、line plot【折线图】

star2、scatter plot【散点图】

star3、bar plot【条形图】

star4、imshow plot【格子图】

5、contour plot【等高线图】

6、quiver plot【箭头】

star7、pie plot【饼图】

star8、text plot【添加文本】

9、fill_between plot【曲线填充图】

10、step plot【阶梯图】

star11、box plot【箱图】

12、errorbar plot【误差棒】

star13、hist plot【直方图】

star14、violin plot【小提琴图】

15、barbs plot【风羽图】

 16、even plot【栅格图】

17、hexbin plot【二元直方图】

18、xcorr plot【相关图】

star三、多子图绘制

subplot 

add_gridspec 

 add_axes

make_axes_locatable 

star四、文本text设置

文本位置 

 文本属性:字体|字号|磅值

star五、注释设置 

注释箭头形状设置

注释箭头弯曲度设置

star五、坐标轴刻度Tick设置 

刻度间距设置 

刻度标签格式化输出 

star六、图例(legend)设置

starstar七、Colors和Colormaps

star八、line和marker设置

star九、子图与figure之间位置


star一、Matplotlib使用Tips

  • Matplotlib获取帮助途径

当使用Matplotlib遇到问题时,可通过以下6条路径获取:

Matplotlib官网:https://matplotlib.org/ 
github:https://github.com/matplotlib/matplotlib/issues
discourse:https://discourse.matplotlib.org
stackoverflow:https://stackoverflow.com/questions/tagged/matplotlib
twitter:https://twitter.com/matplotlib
matplotlib-users:https://mail.python.org/mailman/listinfo/matplotlib-users

  • 绘图十规则

参考:Rougier N P, Droettboom M, Bourne P E, et al. Ten Simple Rules for Better Figures[J]. PLOS Computational Biology【IF 4.7】, 2014, 10(9).

感兴趣戳:https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4161295/pdf/pcbi.1003833.pdf

1. Know Your Audience
2. Identify Your Message
3. Adapt the Figure
4. Captions Are Not Optional
5. Do Not Trust the Defaults
6. Use Color Effectively
7. Do Not Mislead the Reader
8. Avoid “Chartjunk”
9. Message Trumps Beauty
10. Get the Right Too 
  • 常见绘图设置问题

… resize a figure?
fig.set_size_inches(w,h) 
… save a figure?
fig.savefig(”figure.pdf”)
… save a transparent figure?
fig.savefig(”figure.pdf”, transparent=True)
… clear a figure?
ax.clear()
… close all figures?
plt.close(”all”)
… remove ticks?
ax.set_xticks([])
… remove tick labels ?
ax.set_[xy]ticklabels([])
… rotate tick labels ?
ax.set_[xy]ticks(rotation=90)
… hide top spine?
ax.spines[’top’].set_visible(False)
… hide legend border?
ax.legend(frameon=False)
… show error as shaded region?
ax.fill_between(X, Y+error, Y‐error)
… draw a rectangle?
ax.add_patch(plt.Rectangle((0, 0),1,1)
… draw a vertical line?
ax.axvline(x=0.5)
… draw outside frame?
ax.plot(…, clip_on=False)
… use transparency?
ax.plot(…, alpha=0.25)
… convert an RGB image into a gray image?
gray = 0.2989*R+0.5870*G+0.1140*B
… set figure background color?
fig.patch.set_facecolor(“grey”)
… get a reversed colormap?
plt.get_cmap(“viridis_r”)
… get a discrete colormap?
plt.get_cmap(“viridis”, 10)
… show a figure for one second?
fig.show(block=False), time.sleep(1) 
ax. grid ()
ax.patch. set_alpha (0)
ax. set_[xy]lim (vmin, vmax)
ax. set_[xy]label (label)
ax. set_[xy]ticks (list)
ax. set_[xy]ticklabels (list)
ax. set_[sup]title (title)
ax. tick_params (width=10, …)
ax. set_axis_[on|off] ()
ax. tight_layout ()
plt. gcf (), plt. gca ()
mpl. rc (’axes’, linewidth=1, …)
fig.patch. set_alpha (0)
text=r’$\frac{-e^{i\pi}}{2^n}$’

二、图形快速绘制

 

star1、line plot【折线图】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])


X = np.linspace(0, 10, 100)
Y = 4+2*np.sin(2*X)
ax.plot(X, Y, color="C1", linewidth=0.75)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.grid(linewidth=0.125)
plt.show()

 

star2、scatter plot【散点图】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])


np.random.seed(3)
X = 4+np.random.normal(0, 1.25, 24)
Y = 4+np.random.normal(0, 1.25, len(X))
ax.scatter(X, Y, 55, zorder=10,
           edgecolor="white", facecolor="C1", linewidth=0.25)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.grid(linewidth=0.125)
plt.show()

star3、bar plot【条形图】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])
np.random.seed(3)
X = 0.5 + np.arange(8)
Y = np.random.uniform(2, 7, len(X))
ax.bar(X, Y, bottom=0, width=1, 
       edgecolor="white", facecolor="C1", linewidth=0.25)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

star4、imshow plot【格子图】

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


my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])
np.random.seed(3)
I = np.zeros((8,8,4))
I[:,:] = mpl.colors.to_rgba("C1")
I[...,3] = np.random.uniform(0.25,1.0,(8,8))
ax.imshow(I, extent=[0,8,0,8], interpolation="nearest")
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.grid(linewidth=0.25, color="white")
plt.show()

 

5、contour plot【等高线图】

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


my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(1)
X, Y = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Z = (1 - X/2. + X**5 + Y**3)*np.exp(-X**2-Y**2)
Z = Z - Z.min()
colors = np.zeros((5,4))
colors[:] = mpl.colors.to_rgba("C1")
colors[:,3] = np.linspace(0.15, 0.85, len(colors))
plt.contourf(Z, len(colors), extent=[0,8,0,8], colors=colors)
plt.contour(Z, len(colors), extent=[0,8,0,8], colors="white", linewidths=0.125,
            nchunk=10)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
plt.show()

6、quiver plot【箭头】

quiver在可视化梯度变化时非常有用。

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


my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(1)
T = np.linspace(0, 2*np.pi, 8)
X, Y = 4 + 1*np.cos(T), 4 + 1*np.sin(T)
U, V = 1.5*np.cos(T), 1.5*np.sin(T)
plt.quiver(X, Y, U, V, color="C1",
           angles='xy', scale_units='xy', scale=0.5, width=.05)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125, color="0.75")
plt.show()

star7、pie plot【饼图】

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


my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

X = 1,2,3,4
colors = np.zeros((len(X),4))
colors[:] = mpl.colors.to_rgba("C1")
colors[:,3] = np.linspace(0.25, 0.75, len(X))
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.25, color="0.75")
ax.pie(X, colors=["white",]*len(X), radius=3, center=(4,4), 
        wedgeprops = {"linewidth": 0.25, "edgecolor": "white"}, frame=True)
ax.pie(X, colors=colors, radius=3, center=(4,4), 
        wedgeprops = {"linewidth": 0.25, "edgecolor": "white"}, frame=True)

plt.show()

star8、text plot【添加文本】

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


my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.25, color="0.75")
ax.text(4, 4, "TEXT", color="C1", size=38, weight="bold",
        ha="center", va="center", rotation=25)

plt.show()

9、fill_between plot【曲线填充图】

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


my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])


np.random.seed(1)
X = np.linspace(0, 8, 16)
Y1 = 3 + 4*X/8 + np.random.uniform(0.0, 0.5, len(X))
Y2 = 1 + 2*X/8 + np.random.uniform(0.0, 0.5, len(X))
plt.fill_between(X, Y1, Y2, color="C1", alpha=.5, linewidth=0)
plt.plot(X, (Y1+Y2)/2, color="C1", linewidth=0.5)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125, color="0.75")

10、step plot【阶梯图】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

X = np.linspace(0, 10, 16)
Y = 4+2*np.sin(2*X)
ax.step(X, Y, color="C1", linewidth=0.75)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.grid(linewidth=0.125)

star11、box plot【箱图】

  • 快速教程:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(10)
D = np.random.normal((3,5,4), (1.25, 1.00, 1.25), (100,3))
VP = ax.boxplot(D, positions=[2,4,6], widths=1.5, patch_artist=True,
                showmeans=False, showfliers=False,
                medianprops = {"color": "white",
                               "linewidth": 0.25},
                boxprops = {"facecolor": "C1",
                            "edgecolor": "white",
                            "linewidth": 0.25},
                whiskerprops = {"color": "C1",
                                "linewidth": 0.75},
                capprops = {"color": "C1",
                            "linewidth": 0.75})
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

12、errorbar plot【误差棒】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(1)
X = [2,4,6]
Y = [4,5,4]
E = np.random.uniform(0.5, 1.5, 3)
ax.errorbar(X, Y, E, color="C1", linewidth=0.75, capsize=1)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

star13、hist plot【直方图】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(1)
X = 4 + np.random.normal(0,1.5,200)
ax.hist(X, bins=8, facecolor="C1", linewidth=0.25, edgecolor="white",)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 80), ax.set_yticks(np.arange(1,80,10))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

 

star14、violin plot【小提琴图】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(10)
D = np.random.normal((3,5,4), (0.75, 1.00, 0.75), (200,3))
VP = ax.violinplot(D, [2,4,6], widths=1.5,
                   showmeans=False, showmedians=False, showextrema=False)
for body in VP['bodies']:
    body.set_facecolor('C1')
    body.set_alpha(1)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

15、barbs plot【风羽图

气象学中常用图。

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(1)
X = [[2,4,6]]
Y = [[1.5,3,2]]
U = -np.ones((1,3))*0
V = -np.ones((1,3))*np.linspace(50,100,3)
ax.barbs(X,Y,U,V, barbcolor="C1", flagcolor="C1", length=15, linewidth=0.5)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

 16、even plot【栅格图】

神经生物学中常用。

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(1)
X = [2,4,6]
D = np.random.gamma(4, size=(3, 50))
ax.eventplot(D, colors="C1", orientation="vertical", lineoffsets=X, linewidth=0.45)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

17、hexbin plot【二元直方图

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(1)
X = np.random.uniform(1.5,6.5,100)
Y = np.random.uniform(1.5,6.5,100)
C = np.random.uniform(0,1,10000)
ax.hexbin(X, Y, C, gridsize=4, linewidth=0.25, edgecolor="white",
          cmap=plt.get_cmap("Wistia"), alpha=1.0)
ax.set_xlim(0, 8), ax.set_xticks(np.arange(1,8))
ax.set_ylim(0, 8), ax.set_yticks(np.arange(1,8))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)

18、xcorr plot【相关图】

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
mpl.rcParams['axes.linewidth'] = 0.5
mpl.rcParams['xtick.major.size'] = 0.0
mpl.rcParams['ytick.major.size'] = 0.0
mpl.rcParams['axes.unicode_minus'] =False
d = 0.01
ax = fig.add_axes([d,d,1-2*d,1-2*d])

np.random.seed(3)
Y = np.random.uniform(-4, 4, 250)
X = np.random.uniform(-4, 4, 250)
ax.xcorr(X, Y, usevlines=True, maxlags=6, normed=True, lw=2,
         color="C1")
ax.set_xlim(-8, 8), ax.set_xticks(np.arange(-8,8,2))
ax.set_ylim(-.25, .25), ax.set_yticks(np.linspace(-.25,.25,9))
ax.set_axisbelow(True)
ax.grid(linewidth=0.125)
plt.show()


star三、多子图绘制

subplot 

  • 官网教程:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
margin = 0.01
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)


nrows, ncols = 3,3
for i in range(nrows*ncols):
    ax = plt.subplot(ncols, nrows, i+1)
    ax.set_xticks([]), ax.set_yticks([])

add_gridspec 

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
margin = 0.01
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)

gs = fig.add_gridspec(3, 3)
ax1 = fig.add_subplot(gs[0, :], xticks=[], yticks=[])
ax2 = fig.add_subplot(gs[1, :-1], xticks=[], yticks=[])
ax3 = fig.add_subplot(gs[1:, -1], xticks=[], yticks=[])
ax4 = fig.add_subplot(gs[-1, 0], xticks=[], yticks=[])
ax5 = fig.add_subplot(gs[-1, -2], xticks=[], yticks=[])

 

 add_axes

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
margin = 0.01
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)

margin = 0.0125
ax1 = fig.add_axes([margin,margin,1-2*margin,1-2*margin], xticks=[], yticks=[])
ax2 = ax1.inset_axes([0.5, 0.5, 0.4, 0.4], xticks=[], yticks=[])

 

make_axes_locatable 

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

my_dpi=126
fig = plt.figure(figsize=(580/my_dpi,480/my_dpi))
margin = 0.01
fig.subplots_adjust(left=margin, right=1-margin, top=1-margin, bottom=margin)
mpl.rc('axes', linewidth=.5)

from mpl_toolkits.axes_grid1 import make_axes_locatable
margin = 0.0125
ax = fig.add_axes([margin,margin,1-2*margin,1-2*margin], xticks=[], yticks=[])
divider = make_axes_locatable(ax)
cax = divider.new_horizontal(size="10%", pad=0.025)
fig.add_axes(cax)
cax.set_xticks([]), cax.set_yticks([])
plt.show()

 


star四、文本text设置

文本位置 

import numpy as np
import matplotlib.pyplot as plt

dpi = 100
fig = plt.figure(dpi=100)
ax = fig.add_axes([0,0,1,1], frameon=False,
                  xlim=(0,4.25), ylim=(0,1.5), xticks=[], yticks=[])

fontsize = 48
renderer = fig.canvas.get_renderer()
horizontalalignment = "left"
verticalalignment = "center"
position = (0.25, 1.5/2)
color = "0.25"

# Compute vertical and horizontal alignment offsets
text = ax.text(0, 0, "Matplotlib", fontsize=fontsize)
yoffset = {}
for alignment in ["top", "center", "baseline", "bottom"]:
    text.set_verticalalignment(alignment)
    y = text.get_window_extent(renderer).y0/dpi
    yoffset[alignment] = y

xoffset = {}
for alignment in ["left", "center", "right"]:
    text.set_horizontalalignment(alignment)
    x = text.get_window_extent(renderer).x0/dpi
    xoffset[alignment] = x

# Actual positioning of the text
text.set_horizontalalignment(horizontalalignment)
text.set_verticalalignment(verticalalignment)
text.set_position(position)


for name,y in yoffset.items():
    y = position[1] - y + yoffset[verticalalignment]
    plt.plot([0.1, 3.75], [y, y], linewidth=0.5, color=color)
    plt.text(3.75, y, " "+name, color=color,
             ha="left", va="center", size="x-small")

for name,x in xoffset.items():
    x = position[0] - x + xoffset[horizontalalignment]
    plt.plot([x,x], [0.25, 1.25], linewidth=0.5, color=color)
    plt.text(x, 0.24, name, color = color,
             ha="center", va="top", size="x-small")

P = []
for x in xoffset.values():
    x = position[0] - x + xoffset[horizontalalignment]
    for y in yoffset.values():
        y = position[1] - y + yoffset[verticalalignment]
        P.append((x,y))
P = np.array(P)

ax.scatter(P[:,0], P[:,1], s=10, zorder=10,
           facecolor="white", edgecolor=color, linewidth=0.75)

epsilon = 0.05
plt.text(P[3,0]+epsilon, P[3,1]-epsilon, "(0,0)",
         color=color, ha="left", va="top", size="xx-large")
plt.text(P[8,0]-epsilon, P[8,1]+epsilon, "(1,1)",
         color=color, ha="right", va="bottom", size="xx-large")

plt.show()

 文本属性:字体|字号|磅值


star五、注释设置 

#注释(annotate)
#https://matplotlib.org/api/_as_gen/matplotlib.pyplot.annotate.html
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt


fig = plt.figure(figsize=(6,1))
#ax = plt.subplot(111, frameon=False, aspect=.1)
# b = 0.0
ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)



plt.scatter([5.5],[0.75], s=100, c="k")
plt.xlim(0,6), plt.ylim(0,1)
plt.xticks([]), plt.yticks([])

plt.annotate("Annotation", (5.5,.75), (0.1,.75), size=16, va="center",
             arrowprops=dict(facecolor='black', shrink=0.05))

plt.text( 5.5, 0.6, "xy\nycoords", size=10, va="top", ha="center", color=".5")
plt.text( .75, 0.6, "xytext\ntextcoords", size=10, va="top", ha="center", color=".5")
plt.show()

##注释(annotate)箭头类型
#https://matplotlib.org/tutorials/text/annotations.html
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

styles = mpatches.ArrowStyle.get_styles()
def demo_con_style(ax, connectionstyle):
    ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
            family="Source Code Pro",
            transform=ax.transAxes, ha="left", va="top", size="x-small")

fig, ax = plt.subplots(dpi=100, frameon=False)
ax.axis("off")
for i,style in enumerate(mpatches.ArrowStyle.get_styles()):
    x0, y0 = 5 + 5*(i%3), -(i//3)
    x1, y1 = 1 + 5*(i%3), -(i//3)
    ax.plot([x0, x1], [y0, y1], ".", color="0.25")
    ax.annotate("",
                xy=(x0, y0), xycoords='data',
                xytext=(x1, y1), textcoords='data',
                arrowprops=dict(arrowstyle=style,
                                color="black",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle="arc3,rad=0"))
    ax.text( (x1+x0)/2, y0-0.2, style,
             family = "Source Code Pro", ha="center", va="top")
plt.show()

注释箭头形状设置

注释箭头弯曲度设置

#注释(annotate)箭头线型
import matplotlib.pyplot as plt

def demo_con_style(ax, connectionstyle):
    x1, y1 = 0.3, 0.2
    x2, y2 = 0.8, 0.6
    ax.plot([x1, x2], [y1, y2], ".")
    ax.annotate("",
                xy=(x1, y1), xycoords='data',
                xytext=(x2, y2), textcoords='data',
                arrowprops=dict(arrowstyle="->", color="0.5",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle=connectionstyle),
                )
    ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
            family="Source Code Pro",
            transform=ax.transAxes, ha="left", va="top", size="x-small")

fig, axs = plt.subplots(3, 3, dpi=100)
demo_con_style(axs[0, 0], "arc3,rad=0")
demo_con_style(axs[0, 1], "arc3,rad=0.3")
demo_con_style(axs[0, 2], "angle3,angleA=0,angleB=90")
demo_con_style(axs[1, 0], "angle,angleA=-90,angleB=180,rad=0")
demo_con_style(axs[1, 1], "angle,angleA=-90,angleB=180,rad=25")
demo_con_style(axs[1, 2], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
demo_con_style(axs[2, 0], "bar,fraction=0.3")
demo_con_style(axs[2, 1], "bar,fraction=-0.3")
demo_con_style(axs[2, 2], "bar,angle=180,fraction=-0.2")

for ax in axs.flat:
    ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
fig.tight_layout(pad=0.2)
plt.show()


star五、坐标轴刻度Tick设置 

刻度间距设置 

#https://matplotlib.org/api/ticker_api.html
#刻度间距设置
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Setup a plot such that only the bottom spine is shown
def setup(ax):
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00)
    ax.tick_params(which='major', length=5)
    ax.tick_params(which='minor', width=0.75)
    ax.tick_params(which='minor', length=2.5)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.patch.set_alpha(0.0)


fig = plt.figure(figsize=(8, 5))
fig.patch.set_alpha(0.0)
n = 8

fontsize = 18
family = "Source Code Pro"

# Null Locator
ax = plt.subplot(n, 1, 1)
setup(ax)
ax.xaxis.set_major_locator(ticker.NullLocator())
ax.xaxis.set_minor_locator(ticker.NullLocator())
ax.text(0.0, 0.1, "ticker.NullLocator()",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Multiple Locator
ax = plt.subplot(n, 1, 2)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(0.5))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
ax.text(0.0, 0.1, "ticker.MultipleLocator(0.5)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Fixed Locator
ax = plt.subplot(n, 1, 3)
setup(ax)
majors = [0, 1, 5]
ax.xaxis.set_major_locator(ticker.FixedLocator(majors))
minors = np.linspace(0, 1, 11)[1:-1]
ax.xaxis.set_minor_locator(ticker.FixedLocator(minors))
ax.text(0.0, 0.1, "ticker.FixedLocator([0, 1, 5])",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Linear Locator
ax = plt.subplot(n, 1, 4)
setup(ax)
ax.xaxis.set_major_locator(ticker.LinearLocator(3))
ax.xaxis.set_minor_locator(ticker.LinearLocator(31))
ax.text(0.0, 0.1, "ticker.LinearLocator(numticks=3)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Index Locator
ax = plt.subplot(n, 1, 5)
setup(ax)
ax.plot(range(0, 5), [0]*5, color='white')
ax.xaxis.set_major_locator(ticker.IndexLocator(base=.5, offset=.25))
ax.text(0.0, 0.1, "ticker.IndexLocator(base=0.5, offset=0.25)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Auto Locator
ax = plt.subplot(n, 1, 6)
setup(ax)
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.text(0.0, 0.1, "ticker.AutoLocator()",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# MaxN Locator
ax = plt.subplot(n, 1, 7)
setup(ax)
ax.xaxis.set_major_locator(ticker.MaxNLocator(4))
ax.xaxis.set_minor_locator(ticker.MaxNLocator(40))
ax.text(0.0, 0.1, "ticker.MaxNLocator(n=4)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Log Locator
ax = plt.subplot(n, 1, 8)
setup(ax)
ax.set_xlim(10**3, 10**10)
ax.set_xscale('log')
ax.xaxis.set_major_locator(ticker.LogLocator(base=10.0, numticks=15))
ax.text(0.0, 0.1, "ticker.LogLocator(base=10, numticks=15)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Push the top of the top axes outside the figure because we only show the
# bottom spine.
plt.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=1.05)

刻度标签格式化输出 

# 刻度格式化输出
# https://matplotlib.org/api/ticker_api.html
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

# Setup a plot such that only the bottom spine is shown
def setup(ax):
    ax.spines['right'].set_color('none')
    ax.spines['left'].set_color('none')
    ax.yaxis.set_major_locator(ticker.NullLocator())
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.tick_params(which='major', width=1.00, length=5)
    ax.tick_params(which='minor', width=0.75, length=2.5, labelsize=10)
    ax.set_xlim(0, 5)
    ax.set_ylim(0, 1)
    ax.patch.set_alpha(0.0)


fig = plt.figure(figsize=(8, 5))
fig.patch.set_alpha(0.0)
n = 7

fontsize = 18
family = "Source Code Pro"

# Null formatter
ax = fig.add_subplot(n, 1, 1)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(ticker.NullFormatter())
ax.text(0.0, 0.1, "ticker.NullFormatter()", family=family,
        fontsize=fontsize, transform=ax.transAxes)

# Fixed formatter
ax = fig.add_subplot(n, 1, 2)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
majors = ["", "0", "1", "2", "3", "4", "5"]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(majors))
minors = [""] + ["%.2f" % (x-int(x)) if (x-int(x))
                 else "" for x in np.arange(0, 5, 0.25)]
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(minors))
ax.text(0.0, 0.1, "ticker.FixedFormatter(['', '0', '1', ...])",
        family=family, fontsize=fontsize, transform=ax.transAxes)


# FuncFormatter can be used as a decorator
@ticker.FuncFormatter
def major_formatter(x, pos):
    return "[%.2f]" % x


ax = fig.add_subplot(n, 1, 3)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(major_formatter)
ax.text(0.0, 0.1, 'ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x)',
        family=family, fontsize=fontsize, transform=ax.transAxes)


# FormatStr formatter
ax = fig.add_subplot(n, 1, 4)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter(">%d<"))
ax.text(0.0, 0.1, "ticker.FormatStrFormatter('>%d<')",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Scalar formatter
ax = fig.add_subplot(n, 1, 5)
setup(ax)
ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
ax.xaxis.set_major_formatter(ticker.ScalarFormatter(useMathText=True))
ax.text(0.0, 0.1, "ticker.ScalarFormatter()",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# StrMethod formatter
ax = fig.add_subplot(n, 1, 6)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x}"))
ax.text(0.0, 0.1, "ticker.StrMethodFormatter('{x}')",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Percent formatter
ax = fig.add_subplot(n, 1, 7)
setup(ax)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.00))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
ax.xaxis.set_major_formatter(ticker.PercentFormatter(xmax=5))
ax.text(0.0, 0.1, "ticker.PercentFormatter(xmax=5)",
        family=family, fontsize=fontsize, transform=ax.transAxes)

# Push the top of the top axes outside the figure because we only show the
# bottom spine.
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=1.05)


star六、图例(legend)设置

#图例(legend)|位置
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt


fig = plt.figure(figsize=(4,4))
ax = fig.add_axes([0.15,0.15,.7,.7], frameon=True, aspect=1,
                  xticks=[], yticks=[])

def text(x, y, _text):
    color= "C1"
    if not 0 < x < 1 or not 0 < y < 1:  color = "C0"
    size = 0.15
    ax.text(x, y, _text, color="white", #bbox={"color": "C1"},
            size="xx-large", weight="bold", ha="center", va="center")
    rect = plt.Rectangle((x-size/2, y-size/2), size, size, facecolor=color,
                         zorder=-10, clip_on=False)
    ax.add_patch(rect)

def point(x, y):
    ax.scatter([x], [y], facecolor="C0", edgecolor="white",
               zorder=10, clip_on=False)

d = .1
e = .15/2

text(  d,   d, "1"), text( 0.5,   d, "2"), text(1-d,   d, "3")
text(  d, 0.5, "4"), text( 0.5, 0.5, "5"), text(1-d, 0.5, "6")
text(  d, 1-d, "7"), text( 0.5, 1-d, "8"), text(1-d, 1-d, "9")

text( -d, 1-d, "A"), text( -d, 0.5, "B"), text(  -d,   d, "C")
point(-d+e, 1-d+e), point(-d+e, 0.5), point(-d+e, d-e),

text(  d,  -d, "D"), text(0.5,  -d, "E"), text( 1-d,  -d, "F")
point(d-e, -d+e), point(0.5, -d+e), point(1-d+e, -d+e),

text(1+d,   d, "G"), text(1+d, 0.5, "H"), text( 1+d, 1-d, "I")
point(1+d-e, d-e), point(1+d-e, .5), point(1+d-e, 1-d+e),

text(1-d, 1+d, "J"), text(0.5, 1+d, "K"), text(   d, 1+d, "L")
point(1-d+e, 1+d-e), point(0.5, 1+d-e), point(d-e, 1+d-e),

plt.xlim(0,1), plt.ylim(0,1)
plt.show()

1: lower left 2: lower center 3: lower right
4: left 5: center 6: right
7: upper left 8: upper center 9: upper right
A: upper right / (‐.1,.9) B: right / (‐.1,.5)
C: lower right / (‐.1,.1) D: upper left / (‐.1,‐.1)
E: upper center / (.5,‐.1) F: upper right / (.9,‐.1)
G: lower left / (1.1,.1) H: left / (1.1,.5)
I: upper left / (1.1,.9) J: lower right / (.9,1.1)
K: lower center / (.5,1.1) L: lower left / (.1,1.1) 

starstar七、Colors和Colormaps

  • 实战详细教程:

关于颜色使用,之前花了不少精力整理:

Python可视化|matplotlib05-内置单颜色(一)
Python可视化|matplotlib06-外部单颜色(二)
Python可视化|matplotlib07-自带颜色条Colormap(三)
Python可视化|08-Palettable库中颜色条Colormap(四)
Python|R可视化|09-提取图片颜色绘图(五)
颜色cheatsheet(一)
颜色cheatsheet(二)
Python可视化18|seaborn-seaborn调色盘 


star八、line和marker设置


star九、子图与figure之间位置

# figure中子图位置调整
#matplotlib.pyplot.subplots_adjust
#https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection


fig = plt.figure(dpi=120)
ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1,
                  xlim=(0-5,100+10), ylim=(-10,80+5), xticks=[], yticks=[])


box = mpatches.FancyBboxPatch(
    (0,0), 100, 83,  mpatches.BoxStyle("Round", pad=0, rounding_size=2),
    linewidth=1., facecolor="0.9", edgecolor="black")
ax.add_artist(box)

box = mpatches.FancyBboxPatch(
    (0,0), 100, 75, mpatches.BoxStyle("Round", pad=0, rounding_size=0),
    linewidth=1., facecolor="white", edgecolor="black")
ax.add_artist(box)


box = mpatches.Rectangle(
    (5,5), 45, 30, zorder=10,
    linewidth=1.0, facecolor="white", edgecolor="black")
ax.add_artist(box)

box = mpatches.Rectangle(
    (5,40), 45, 30, zorder=10,
    linewidth=1.0, facecolor="white", edgecolor="black")
ax.add_artist(box)

box = mpatches.Rectangle(
    (55,5), 40, 65, zorder=10,
    linewidth=1.0, facecolor="white", edgecolor="black")
ax.add_artist(box)

# Window button
X, Y = [5,10,15], [79,79,79]
plt.scatter(X, Y, s=75,  zorder=10,
            edgecolor="black", facecolor="white", linewidth=1)


# Window size extension
X, Y = [0, 0], [0, -8]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)

X, Y = [100, 100], [0, -8]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)

X, Y = [100, 108], [0, 0]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)

X, Y = [100, 108], [75, 75]
plt.plot(X, Y, color="black", linestyle=":", linewidth=1, clip_on=False)


def ext_arrow(p0,p1,p2,p3):
    p0, p1 = np.asarray(p0), np.asarray(p1)
    p2, p3 = np.asarray(p2), np.asarray(p3)
    ax.arrow(*p0, *(p1-p0), zorder=20, linewidth=0,
             length_includes_head=True, width=.4, 
             head_width=2, head_length=2, color="black")
    ax.arrow(*p3, *(p2-p3), zorder=20, linewidth=0,
             length_includes_head=True, width=.4,
             head_width=2, head_length=2, color="black")
    plt.plot([p1[0],p2[0]], [p1[1],p2[1]], linewidth=.9, color="black")

def int_arrow(p0,p1):
    p0, p1 = np.asarray(p0), np.asarray(p1)
    ax.arrow(*((p0+p1)/2), *((p1-p0)/2), zorder=20, linewidth=0,
             length_includes_head=True, width=.4, 
             head_width=2, head_length=2, color="black")
    ax.arrow(*((p0+p1)/2), *(-(p1-p0)/2), zorder=20, linewidth=0,
             length_includes_head=True, width=.4, 
             head_width=2, head_length=2, color="black")

    

x = 0
y = 10
ext_arrow( (x-4,y), (x,y), (x+5,y), (x+9,y) )
ax.text(x+9.5, y, "left", ha="left", va="center", size="x-small", zorder=20)

x += 50
ext_arrow( (x-4,y), (x,y), (x+5,y), (x+9,y) )
ax.text(x-4.5, y, "wspace", ha="right", va="center", size="x-small", zorder=20)

x += 45
ext_arrow( (x-4,y), (x,y), (x+5,y), (x+9,y) )
ax.text(x-4.5, y, "right", ha="right", va="center", size="x-small", zorder=20)

y = 0
x = 25
ext_arrow( (x,y-4), (x,y), (x,y+5), (x,y+9) )
ax.text(x, y+9.5, "bottom", ha="center", va="bottom", size="x-small", zorder=20)

y += 35
ext_arrow( (x,y-4), (x,y), (x,y+5), (x,y+9) )
ax.text(x, y-4.5, "hspace", ha="center", va="top", size="x-small", zorder=20)

y += 35
ext_arrow( (x,y-4), (x,y), (x,y+5), (x,y+9) )
ax.text(x, y-4.5, "top", ha="center", va="top", size="x-small", zorder=20)

int_arrow((0,-5), (100,-5))
ax.text(50, -5, "figure width", backgroundcolor="white", zorder=30,
        ha="center", va="center", size="x-small")

int_arrow((105,0), (105,75))
ax.text(105, 75/2, "figure height", backgroundcolor="white", zorder=30,
        rotation = "vertical", ha="center", va="center", size="x-small")

int_arrow((55,62.5), (95,62.5))
ax.text(75, 62.5, "axes width", backgroundcolor="white", zorder=30,
        ha="center", va="center", size="x-small")

int_arrow((62.5,5), (62.5,70))
ax.text(62.5, 35, "axes height", backgroundcolor="white", zorder=30,
        rotation = "vertical", ha="center", va="center", size="x-small")
plt.show()