查看原文
其他

详解Python Matplotlib (pyplot法)

pythonic生物人 pythonic生物人 2022-12-04

pythonic生物人」👇系统分享数据科学干货,下划线点击直达👉:Python可视化R可视化Python精进图解统计学机器学习等,一起来精进吧!

  • Matplotlib中提供了两种绘图方法:
    类似MATLAB方法:使用matplotlib.pyplot;
    面向对象方法:主要使用matplotlib.figure.Figure和matplotlib.axes.Axes。
  • 本文详解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=(98), 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 = [020 / 25682 / 256]

# 准备绘图数据
np.random.seed(19680801)
X = np.linspace(0.53.5120)
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(04)
plt.ylim(04)

# 设置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=(44),
    xytext=(4.22.2),
    color=(0.250.251.00),
    weight="regular",
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="black"),
)

plt.annotate(
    "",
    xy=(40),
    xytext=(4.21.8),
    color=(0.250.251.00),
    weight="regular",
    arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="black"),
)

# 矩形外框
fig.add_artist(
    Rectangle((00),
              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=(1111))])
    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=(1111))])


# 图中添加Matplotlib对应方法文本
def code(x, y, text):
    plt.text(x,
             y,
             text,
             zorder=100,
             ha='center',
             va='top',
             weight='normal',
             color=(0.250.251.00),
             fontsize='medium',
             path_effects=[withStroke(linewidth=7, foreground=(1111))])


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.3854.3"Figure""plt.figure")

circle(4.32.2"子图, 整个阴影部分""plt.axes")
circle(-0.804.43"Figure标题""fig.suptitle")
circle(1.124.13"子图标题""plt.title")

circle(1.752.80"折线图""plt.plot")
circle(1.51.64"标记形状""plt.plot,marker")
circle(3.003.00"网格线""plt.grid")
circle(2.83.65"图例""plt.legend")

circle(-0.031.05"主刻度""plt.gca().yaxis.set_major_locator")
circle(-0.153.00"主刻度标签""plt.gca().yaxis.set_major_formatter")
circle(0.003.75"副刻度""plt.gca().yaxis.set_minor_locator")
circle(3.25-0.10"副刻度标签""plt.gca().xaxis.set_minor_formatter")

circle(0.650.01"x轴""plt.gca().xaxis")
circle(00.44"y轴""plt.gca().yaxis")
circle(1.650-0.32"x轴标题""plt.xlabel")
circle(-0.471.68"y轴标题""plt.ylabel")

circle(4.00.7"图脊, 边界线""plt.gca().spines")
circle(-1.17-0.22"矩形外框""fig.add_artist")

circle(4.13.5"文本、箭头""plt.annotate/text")

plt.show()
-END-

pythonic生物人」👇系统分享数据科学干货,下划线点击直达👉:Python可视化R可视化Python精进图解统计学机器学习等,一起来精进吧!

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存