• 一图胜千言,200行代码图解Python Matplotlib (面向对象法)!


    本文是那本书翻译的第三篇(参考Fundamentals部分及Matplotlib.org),不明白说的什么👇

    打算翻译下这本书!

    从PyViz到Matplotlib

    Matplotlib中提供了两种绘图方法:

    • 类似MATLAB方法:使用matplotlib.pyplot;

    • 面向对象方法:主要使用matplotlib.figure.Figure和matplotlib.axes.Axes。

    本文介绍Matplotlib图形组成 (基于面向对象方法),通过本文基本能掌握Matplotlib面向对象绘图法常用操作,文末如果有人点赞、在看,会尽快更新下一篇:图解Matplotlib (pyplot法)~~。

    废话不多说,上效果图,

    上图参考了matplotlib.org,pythonic生物人做了很多修改,以便于人能看懂。

    通过上图可以轻松学会Figure、title、subplot、axis、grid、legend、ticker、patches、annotate、artist、text等使用。

    结合之前文章一起阅读效果更佳👉Python可视化笔记43篇合集

    上代码,

    1. #!/usr/bin/env python
    2. # -*- encoding: utf-8 -*-
    3. '''
    4. 转载请标明来源!转载请标明来源!转载请标明来源!
    5. @Time : 2022年五一劳动节
    6. @Author : matplotlib.org,公众号:pythonic生物人
    7. @Contact : 公众号:pythonic生物人
    8. @Desc : 图解Matplotlib面向对象方法
    9. '''
    10. # 导入模块
    11. import numpy as np
    12. import matplotlib.pyplot as plt
    13. from matplotlib.patches import Circle, Rectangle
    14. from matplotlib.patheffects import withStroke
    15. from matplotlib.ticker import AutoMinorLocator, MultipleLocator
    16. # 指定字体
    17. from mplfonts import use_font
    18. use_font('Source Han Mono SC')
    19. # 添加画布Figure,图中红框包围的部分为一个Figure
    20. fig = plt.figure(figsize=(9, 8), facecolor='1', dpi=150)
    21. # 为Figure添加标题
    22. fig.suptitle('Matplotlib面向对象法', x=0.46, fontsize=20, ha='right')
    23. # 在Figure上添加子图Axes
    24. marg = 0.15
    25. ax = fig.add_axes([marg, marg, 1 - 1.8 * marg, 1 - 1.8 * marg],
    26. aspect=1,
    27. facecolor='0.9')
    28. # 准备绘图数据
    29. np.random.seed(19680801)
    30. X = np.linspace(0.5, 3.5, 120)
    31. Y1 = 3 + np.cos(X)
    32. Y2 = 1 + np.cos(1 + X / 0.75) / 2
    33. Y3 = np.random.uniform(Y1, Y2, len(X))
    34. # 同一个axes上绘图
    35. ax.plot(X, Y1, c='orange', lw=1, label="Orange signal", zorder=10)
    36. ax.plot(X[::3],
    37. Y3[::3],
    38. linewidth=0,
    39. markersize=6,
    40. marker='*',
    41. markerfacecolor='none',
    42. markeredgecolor='black',
    43. markeredgewidth=1)
    44. # 设置子图标题
    45. ax.set_title("Matplotlib图形元素", fontsize=15, verticalalignment='bottom')
    46. # 设置图例
    47. ax.legend(loc="upper right", fontsize=10)
    48. # 设置坐标轴标题
    49. ax.set_xlabel("x轴标题", fontsize=12)
    50. ax.set_ylabel("y轴标题", fontsize=12)
    51. # 设置x,y轴刻度间隔
    52. ax.xaxis.set_major_locator(MultipleLocator(1.000)) # x轴主刻度间隔
    53. ax.xaxis.set_minor_locator(AutoMinorLocator(4)) # x轴副刻度间隔
    54. ax.yaxis.set_major_locator(MultipleLocator(1.000))
    55. ax.yaxis.set_minor_locator(AutoMinorLocator(4))
    56. # 设置x轴副刻度格式
    57. def minor_tick(x, pos):
    58. if not x % 1.0:
    59. return ""
    60. return f"{x:.2f}"
    61. ax.xaxis.set_minor_formatter(minor_tick)
    62. # 设置x,y轴刻度范围
    63. ax.set_xlim(0, 4)
    64. ax.set_ylim(0, 4)
    65. # 设置x,y轴刻度字号、颜色等
    66. ax.tick_params(which='major', width=1.0, labelsize=12)
    67. ax.tick_params(which='major', length=10, labelsize=12)
    68. ax.tick_params(which='minor', width=1.0, labelsize=10)
    69. ax.tick_params(which='minor', length=5, labelsize=6, labelcolor='0.5')
    70. # 设置网格线
    71. ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10)
    72. # 文本、箭头
    73. ax.annotate(
    74. "",
    75. xy=(4, 4),
    76. xytext=(4.2, 2.2),
    77. color=(0.25, 0.25, 1.00),
    78. weight="regular",
    79. arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="black"),
    80. )
    81. ax.annotate(
    82. "",
    83. xy=(4, 0),
    84. xytext=(4.2, 1.8),
    85. color=(0.25, 0.25, 1.00),
    86. weight="regular",
    87. arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="black"),
    88. )
    89. # 矩形外框
    90. fig.add_artist(
    91. Rectangle((0, 0),
    92. width=1,
    93. height=1,
    94. facecolor='none',
    95. edgecolor='red',
    96. linewidth=1.0))
    97. # 图中添加圆圈注释
    98. def just_circle(x, y, radius=0.15):
    99. c = Circle((x, y),
    100. radius,
    101. clip_on=False,
    102. zorder=10,
    103. linewidth=0.6,
    104. edgecolor='black',
    105. facecolor='none',
    106. path_effects=[withStroke(linewidth=5, foreground=(1, 1, 1, 1))])
    107. ax.add_artist(c)
    108. # 图中添加文本注释
    109. def text(x, y, text):
    110. ax.text(x,
    111. y,
    112. text,
    113. zorder=100,
    114. ha='center',
    115. va='top',
    116. weight='bold',
    117. color='black',
    118. style='italic',
    119. path_effects=[withStroke(linewidth=7, foreground=(1, 1, 1, 1))])
    120. # 图中添加Matplotlib对应方法文本
    121. def code(x, y, text):
    122. ax.text(x,
    123. y,
    124. text,
    125. zorder=100,
    126. ha='center',
    127. va='top',
    128. weight='normal',
    129. color=(0.25, 0.25, 1.00),
    130. fontsize='medium',
    131. path_effects=[withStroke(linewidth=7, foreground=(1, 1, 1, 1))])
    132. def circle(x, y, txt, cde, radius=0.1):
    133. just_circle(x, y, radius=radius)
    134. text(x, y - 0.2, txt)
    135. code(x, y - 0.33, cde)
    136. circle(4.385, 4.3, "Figure", "plt.figure")
    137. circle(4.3, 2.2, "子图, 整个阴影部分", "fig.subplots")
    138. circle(-0.67, 4.43, "Figure标题", "fig.suptitle")
    139. circle(1.08, 4.13, "子图标题", "ax.set_title")
    140. circle(1.75, 2.80, "折线图", "ax.plot")
    141. circle(1.5, 1.64, "标记形状", "ax.plot,marker")
    142. circle(3.00, 3.00, "网格线", "ax.grid")
    143. circle(2.8, 3.65, "图例", "ax.legend")
    144. circle(-0.03, 1.05, "主刻度", "ax.yaxis.set_major_locator")
    145. circle(-0.15, 3.00, "主刻度标签", "ax.yaxis.set_major_formatter")
    146. circle(0.00, 3.75, "副刻度", "ax.yaxis.set_minor_locator")
    147. circle(3.25, -0.10, "副刻度标签", "ax.xaxis.set_minor_formatter")
    148. circle(0.65, 0.01, "x轴", "ax.xaxis")
    149. circle(0, 0.44, "y轴", "ax.yaxis")
    150. circle(1.650, -0.32, "x轴标题", "ax.set_xlabel")
    151. circle(-0.47, 1.68, "y轴标题", "ax.set_ylabel")
    152. circle(4.0, 0.7, "图脊, 边界线", "ax.spines")
    153. circle(-1.17, -0.22, "矩形外框", "fig.add_artist")
    154. circle(4.1, 3.5, "文本、箭头", "ax.annotate/text")
    155. plt.show()

  • 相关阅读:
    【云原生】一文带你吃透FlexManager数据传入华为云IOT
    @Async注解失效及原理
    猿如意---Python3.10版本手把手教学安装和下载.
    单例模式在多线程下的数据修改问题(即线程不安全),spring中是如何保证单例的线程安全问题的
    深度学习Tensorflow: CUDA_ERROR_OUT_OF_MEMORY解决办法
    软件测试自学,这就技术你get了吗?
    [ 常用工具篇 ] kali 忘记 root 密码 -- 修改 root 密码
    python图片上写中文,添加字幕
    MongoDB聚合运算符:$bsonSize
    Design Compiler工具学习笔记(6)
  • 原文地址:https://blog.csdn.net/qq_21478261/article/details/124557024