Python可视化|Matplotlib39-Matplotlib 1.4W+字教程(珍藏版)

Posted qq_21478261

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python可视化|Matplotlib39-Matplotlib 1.4W+字教程(珍藏版)相关的知识,希望对你有一定的参考价值。

  • 本文系统梳理了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\\pi2^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)

python数据可视化(matplotlib)

Python 数据可视化之-[Matplotlib]

Python 数据可视化之-[Matplotlib]

Python matplotlib可视化图形

python使用matplotlib可视化查看matplotlib可视化中不同字体形式不同字号斜体可视化的效果对比

python数据可视化matplotlib的使用