其他
详解Python Matplotlib (pyplot法)
「pythonic生物人」👇系统分享数据科学干货,下划线点击直达👉:Python可视化、R可视化、Python精进、图解统计学、机器学习等,一起来精进吧!
Matplotlib中提供了两种绘图方法:
类似MATLAB方法:使用matplotlib.pyplot;
面向对象方法:主要使用matplotlib.figure.Figure和matplotlib.axes.Axes。本文详解matplotlib.pyplot方法
上图参考了matplotlib.org,pythonic生物人做了很多修改。 通过上图可以轻松学会 Figure、title、subplot、axis、grid、legend、ticker、patches、annotate、artist、text
等使用。图中蓝色字体的大部分方法之前都详细介绍过👉Python可视化笔记43篇合集 强烈建议结合一图胜千言,200行代码图解Matplotlib (面向对象法)!一起比对阅读,会轻松理解Matplotlib (面向对象法)和Matplotlib (pyplot法)区别。
例如,蓝色圈中ax.plot和plt.plot绘制折线的使用区别👇,
上代码,
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
转载请标明来源!转载请标明来源!转载请标明来源!
@Time : '2022-05-18 23:41:28'
@Author : matplotlib.org,公众号:pythonic生物人
@Contact : 公众号:pythonic生物人
@Desc : 图解Matplotlib-pyplot法
'''
# 导入模块
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle
from matplotlib.patheffects import withStroke
from matplotlib.ticker import AutoMinorLocator, MultipleLocator
# 指定字体
from mplfonts import use_font
use_font('Source Han Mono SC')
# 添加画布Figure,图中红框包围的部分为一个Figure
fig = plt.figure(figsize=(9, 8), facecolor='1', dpi=150)
# 为Figure添加标题
fig.suptitle('Matplotlib-pyplot法', x=0.46, fontsize=20, ha='right')
# 设置子图Axes背景色等
marg = 0.15
plt.axes([marg, marg, 1 - 1.8 * marg, 1 - 1.8 * marg],
aspect=1,
facecolor='0.9')
royal_blue = "#002082"
royal_blue = [0, 20 / 256, 82 / 256]
# 准备绘图数据
np.random.seed(19680801)
X = np.linspace(0.5, 3.5, 120)
Y1 = 3 + np.cos(X)
Y2 = 1 + np.cos(1 + X / 0.75) / 2
Y3 = np.random.uniform(Y1, Y2, len(X))
# 同一个axes上绘图
plt.plot(X, Y1, c='orange', lw=1, label="Orange signal", zorder=10)
plt.plot(X[::3],
Y3[::3],
linewidth=0,
markersize=6,
marker='*',
markerfacecolor='none',
markeredgecolor='black',
markeredgewidth=1)
# 设置子图标题
plt.title("Matplotlib图形元素", fontsize=15, verticalalignment='bottom')
# 设置图例
plt.legend(loc="upper right", fontsize=10)
# 设置坐标轴标题
plt.xlabel("x轴标题", fontsize=12)
plt.ylabel("y轴标题", fontsize=12)
# 设置x,y轴刻度间隔
plt.gca().xaxis.set_major_locator(MultipleLocator(1.000)) # x轴主刻度间隔
plt.gca().xaxis.set_minor_locator(AutoMinorLocator(4)) # x轴副刻度间隔
plt.gca().yaxis.set_major_locator(MultipleLocator(1.000))
plt.gca().yaxis.set_minor_locator(AutoMinorLocator(4))
# 设置x轴副刻度格式,小数点后位数
def minor_tick(x, pos):
if not x % 1.0:
return ""
return f"{x:.2f}"
plt.gca().xaxis.set_minor_formatter(minor_tick)
# 设置x,y轴刻度范围
plt.xlim(0, 4)
plt.ylim(0, 4)
# 设置x,y轴刻度字号、颜色等
plt.tick_params(which='major', width=1.0, labelsize=12)
plt.tick_params(which='major', length=10, labelsize=12)
plt.tick_params(which='minor', width=1.0, labelsize=10)
plt.tick_params(which='minor', length=5, labelsize=6, labelcolor='0.5')
# 设置网格线
plt.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
# 文本、箭头
plt.annotate(
"",
xy=(4, 4),
xytext=(4.2, 2.2),
color=(0.25, 0.25, 1.00),
weight="regular",
arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="black"),
)
plt.annotate(
"",
xy=(4, 0),
xytext=(4.2, 1.8),
color=(0.25, 0.25, 1.00),
weight="regular",
arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="black"),
)
# 矩形外框
fig.add_artist(
Rectangle((0, 0),
width=1,
height=1,
facecolor='none',
edgecolor='red',
linewidth=1.0))
# 图中添加圆圈注释
def just_circle(x, y, radius=0.15):
c = Circle((x, y),
radius,
clip_on=False,
zorder=10,
linewidth=0.6,
edgecolor='black',
facecolor='none',
path_effects=[withStroke(linewidth=5, foreground=(1, 1, 1, 1))])
plt.gca().add_artist(c)
# 图中添加文本注释
def text(x, y, text):
plt.text(x,
y,
text,
zorder=100,
ha='center',
va='top',
weight='bold',
color='black',
style='italic',
path_effects=[withStroke(linewidth=7, foreground=(1, 1, 1, 1))])
# 图中添加Matplotlib对应方法文本
def code(x, y, text):
plt.text(x,
y,
text,
zorder=100,
ha='center',
va='top',
weight='normal',
color=(0.25, 0.25, 1.00),
fontsize='medium',
path_effects=[withStroke(linewidth=7, foreground=(1, 1, 1, 1))])
def circle(x, y, txt, cde, radius=0.1):
just_circle(x, y, radius=radius)
text(x, y - 0.2, txt)
code(x, y - 0.33, cde)
circle(4.385, 4.3, "Figure", "plt.figure")
circle(4.3, 2.2, "子图, 整个阴影部分", "plt.axes")
circle(-0.80, 4.43, "Figure标题", "fig.suptitle")
circle(1.12, 4.13, "子图标题", "plt.title")
circle(1.75, 2.80, "折线图", "plt.plot")
circle(1.5, 1.64, "标记形状", "plt.plot,marker")
circle(3.00, 3.00, "网格线", "plt.grid")
circle(2.8, 3.65, "图例", "plt.legend")
circle(-0.03, 1.05, "主刻度", "plt.gca().yaxis.set_major_locator")
circle(-0.15, 3.00, "主刻度标签", "plt.gca().yaxis.set_major_formatter")
circle(0.00, 3.75, "副刻度", "plt.gca().yaxis.set_minor_locator")
circle(3.25, -0.10, "副刻度标签", "plt.gca().xaxis.set_minor_formatter")
circle(0.65, 0.01, "x轴", "plt.gca().xaxis")
circle(0, 0.44, "y轴", "plt.gca().yaxis")
circle(1.650, -0.32, "x轴标题", "plt.xlabel")
circle(-0.47, 1.68, "y轴标题", "plt.ylabel")
circle(4.0, 0.7, "图脊, 边界线", "plt.gca().spines")
circle(-1.17, -0.22, "矩形外框", "fig.add_artist")
circle(4.1, 3.5, "文本、箭头", "plt.annotate/text")
plt.show()
「pythonic生物人」👇系统分享数据科学干货,下划线点击直达👉:Python可视化、R可视化、Python精进、图解统计学、机器学习等,一起来精进吧!