1. Figure和Axes上的文本

Matplotlib具有广泛的文本支持,包括对数学表达式的支持、对栅格和矢量输出的TrueType支持、具有任意旋转的换行分隔文本以及Unicode支持。
下面的命令是介绍了通过pyplot API和objected-oriented API分别创建文本的方式。

pyplot API OO API description
text text Axes的任意位置添加text
title set_title Axes添加title
figtext text Figure的任意位置添加text
suptitle suptitle Figure添加title
xlabel set_xlabel Axes的x-axis添加label
ylabel set_ylabel Axes的y-axis添加label
annotate annotate Axes的任意位置添加带有可选箭头的标注

1.1 text

pyplot API:matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
OO API: Axes.text(self, x, y, s, fontdict=None, **kwargs)

参数**:此方法接受以下描述的参数。

  • s:此参数是要添加的文本。
  • xy:此参数是放置文本的点(x,y)。
  • fontdict:此参数是一个可选参数,并且是一个覆盖默认文本属性的字典。如果fontdict为None,则由rcParams确定默认值。

返回值:此方法返回作为创建的文本实例的文本。

fontdict主要参数具体介绍,更多参数请参考官网说明

Property Description
alpha float or None 该参数指透明度,越接近0越透明,越接近1越不透明
backgroundcolor color 该参数指文本的背景颜色,具体matplotlib支持颜色如下
bbox dict with properties for patches.FancyBboxPatch 这个是用来设置text周围的box外框
color or c color 指的是字体的颜色
fontfamily or family {FONTNAME, ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’} 该参数指的是字体的类型
fontproperties or font or font_properties font_manager.FontProperties or str or pathlib.Path
fontsize or size float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’} 该参数指字体大小
fontstretch or stretch {a numeric value in range 0-1000, ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’} 该参数是指从字体中选择正常、压缩或扩展的字体
fontstyle or style {‘normal’, ‘italic’, ‘oblique’} 该参数是指字体的样式是否倾斜等
fontweight or weight {a numeric value in range 0-1000, ‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’}
horizontalalignment or ha {‘center’, ‘right’, ‘left’} 该参数是指选择文本左对齐右对齐还是居中对齐
label object
linespacing float (multiple of font size)
position (float, float)
rotation float or {‘vertical’, ‘horizontal’} 该参数是指text逆时针旋转的角度,“horizontal”等于0,“vertical”等于90。我们可以根据自己设定来选择合适角度
verticalalignment or va {‘center’, ‘top’, ‘bottom’, ‘baseline’, ‘center_baseline’}
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from matplotlib.font_manager import FontProperties
  4. import numpy as np

fontdict学习的案例
学习的过程中请尝试更换不同的fontdict字典的内容,以便于更好的掌握

  1. #---------设置字体样式,分别是字体,颜色,宽度,大小
  2. font1 = {'family': 'SimSun',#华文楷体
  3. 'alpha':0.7,#透明度
  4. 'color': 'purple',
  5. 'weight': 'normal',
  6. 'size': 16,
  7. }
  8. font2 = {'family': 'Times New Roman',
  9. 'color': 'red',
  10. 'weight': 'normal',
  11. 'size': 16,
  12. }
  13. font3 = {'family': 'serif',
  14. 'color': 'blue',
  15. 'weight': 'bold',
  16. 'size': 14,
  17. }
  18. font4 = {'family': 'Calibri',
  19. 'color': 'navy',
  20. 'weight': 'normal',
  21. 'size': 17,
  22. }
  23. #-----------四种不同字体显示风格-----
  24. #-------建立函数----------
  25. x = np.linspace(0.0, 5.0, 100)
  26. y = np.cos(2*np.pi*x) * np.exp(-x/3)
  27. #-------绘制图像,添加标注----------
  28. plt.plot(x, y, '--')
  29. plt.title('震荡曲线', fontdict=font1)
  30. #------添加文本在指定的坐标处------------
  31. plt.text(2, 0.65, r'$\cos(2 \pi x) \exp(-x/3)$', fontdict=font2)
  32. #---------设置坐标标签
  33. plt.xlabel('Y=time (s)', fontdict=font3)
  34. plt.ylabel('X=voltage(mv)', fontdict=font4)
  35. # 调整图像边距
  36. plt.subplots_adjust(left=0.15)
  37. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图1

常见的中文字体

  • 黑体:SimHei
  • 微软雅黑:Microsoft YaHei
  • 微软正黑体:Microsoft JhengHei
  • 新宋体:NSimSun
  • 新细明体:PMingLiU
  • 细明体:MingLiU
  • 华文新魏:STXinwei
  • 华文行楷:STXingkai
  • 华文隶书:STLliti
  • 花纹琥珀:STHupo
  • 华文彩云:STCaiyun
  • 方正姚体:FZYaoti
  • 方正舒体:FZShuTi
  • 标楷体:DFKai-SB
  • 华文仿宋:STFangsong
  • 华文中宋:STZhongsong
  • 华文宋体:STSong
  • 华文楷体:STKaiti
  • 华文细黑:STXihei
  • 幼圆:YouYuan
  • 隶书:LiSu
  • 楷体_GB 2313:Kaiti_GB2313
  • 仿宋_GB2313:FangSong_GB2313
  • 仿宋:FangSong

1.2 title和set_title

pyplot API:matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
OO API:Axes.set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)

该命令是用来设置axes的标题

参数:此方法接受以下描述的参数:

  • label:str,此参数是要添加的文本
  • fontdict:dict,此参数是控制title文本的外观,默认fontdict如下:

    1. {'fontsize': rcParams['axes.titlesize'],
    2. 'fontweight': rcParams['axes.titleweight'],
    3. 'color': rcParams['axes.titlecolor'],
    4. 'verticalalignment': 'baseline',
    5. 'horizontalalignment': loc}
  • loc:str,{‘center’, ‘left’, ‘right’}默认为center

  • pad:float,该参数是指标题偏离图表顶部的距离,默认为6。
  • y:float,该参数是title所在axes垂向的位置。默认值为1,即title位于axes的顶部。
  • kwargs:该参数是指可以设置的一些奇特文本的属性。

返回值:此方法返回作为创建的title实例的文本。

1.3 figtext和text

pyplot API:matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs)
OO API:text(self, x, y, s, fontdict=None,**kwargs)

参数:此方法接受以下描述的参数:

  • x,y:float,此参数是指在figure中放置文本的位置。一般取值是在[0,1]范围内。使用transform关键字可以更改坐标系。
  • s:str,此参数是指文本
  • fontdict:dict,此参数是一个可选参数,并且是一个覆盖默认文本属性的字典。如果fontdict为None,则由rcParams确定默认值。

返回值:此方法返回作为创建的文本实例的文本。

1.4 suptitle

pyplot API:matplotlib.pyplot.suptitle(t, **kwargs)
OO API:suptitle(self, t, **kwargs)

参数:此方法接受以下描述的参数:

  • t:str,标题的文本
  • x:float,默认值是0.5.该参数是指文本在figure坐标系下的x坐标
  • y:float,默认值是0.95.该参数是指文本在figure坐标系下的y坐标
  • horizontalalignment, ha:该参数是指选择文本水平对齐方式,有三种选择{‘center’, ‘left’, right’},默认值是 ‘center’
  • verticalalignment, va:该参数是指选择文本垂直对齐方式,有四种选择{‘top’, ‘center’, ‘bottom’, ‘baseline’},默认值是 ‘top’
  • fontsize, size:该参数是指文本的大小,默认值是依据rcParams的设置:rcParams[“figure.titlesize”] (default: ‘large’)
  • fontweight, weight:该参数是用来设置字重。默认值是依据rcParams的设置:rcParams[“figure.titleweight”] (default: ‘normal’)
  • fontproperties:None or dict,该参数是可选参数,如果该参数被指定,字体的大小将从该参数的默认值中提取。

返回值:此方法返回作为创建的title实例的文本。

1.5 xlabel和ylabel

pyplot API:

  • matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)   
  • matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None,*, loc=None, **kwargs)

OO API:

  • Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
  • Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None,*, loc=None, **kwargs)


参数**:此方法接受以下描述的参数:

  • xlabel或者ylabel:label的文本
  • labelpad:设置label距离轴(axis)的距离
  • loc:{‘left’, ‘center’, ‘right’},默认为center
  • **kwargs:文本属性

返回值:此方法返回作为创建的xlabel和ylabel实例的文本。

  1. #文本属性的输入一种是通过**kwargs属性这种方式,一种是通过操作 matplotlib.font_manager.FontProperties 方法
  2. #该案例中对于x_label采用**kwargs调整字体属性,y_label则采用 matplotlib.font_manager.FontProperties 方法调整字体属性
  3. #该链接是FontProperties方法的介绍 https://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontProperties
  4. x1 = np.linspace(0.0, 5.0, 100)
  5. y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
  6. font = FontProperties()
  7. font.set_family('serif')
  8. font.set_name('Times New Roman')
  9. font.set_style('italic')
  10. fig, ax = plt.subplots(figsize=(5, 3))
  11. fig.subplots_adjust(bottom=0.15, left=0.2)
  12. ax.plot(x1, y1)
  13. ax.set_xlabel('time [s]', fontsize='large', fontweight='bold')
  14. ax.set_ylabel('Damped oscillation [V]', fontproperties=font)
  15. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图2

1.6 annotate

pyplot API:matplotlib.pyplot.annotate(text, xy, *args,**kwargs)
OO API:Axes.annotate(self, text, xy, *args,**kwargs)

参数:此方法接受以下描述的参数:

  • text:str,该参数是指注释文本的内容
  • xy:该参数接受二维元组(float, float),是指要注释的点。其二维元组所在的坐标系由xycoords参数决定
  • xytext:注释文本的坐标点,也是二维元组,默认与xy相同
  • xycoords:该参数接受 被注释点的坐标系属性,允许的输入值如下: | 属性值 | 含义 | | :—- | :—- | | ‘figure points’ | 以绘图区左下角为参考,单位是点数 | | ‘figure pixels’ | 以绘图区左下角为参考,单位是像素数 | | ‘figure fraction’ | 以绘图区左下角为参考,单位是百分比 | | ‘axes points’ | 以子绘图区左下角为参考,单位是点数(一个figure可以有多个axes,默认为1个) | | ‘axes pixels’ | 以子绘图区左下角为参考,单位是像素数 | | ‘axes fraction’ | 以子绘图区左下角为参考,单位是百分比 | | ‘data’ | 以被注释的坐标点xy为参考 (默认值) | | ‘polar’ | 不使用本地数据坐标系,使用极坐标系 |
  • textcoords :注释文本的坐标系属性,默认与xycoords属性值相同,也可设为不同的值。除了允许输入xycoords的属性值,还允许输入以下两种: | 属性值 | 含义 | | :—- | :—- | | ‘offset points’ | 相对于被注释点xy的偏移量(单位是点) | | ‘offset pixels’ | 相对于被注释点xy的偏移量(单位是像素) |
  • arrowprops:箭头的样式,dict(字典)型数据,如果该属性非空,则会在注释文本和被注释点之间画一个箭头。如果不设置'arrowstyle' 关键字,则允许包含以下关键字: | 关键字 | 说明 | | :—- | :—- | | width | 箭头的宽度(单位是点) | | headwidth | 箭头头部的宽度(点) | | headlength | 箭头头部的长度(点) | | shrink | 箭头两端收缩的百分比(占总长) | | ? | 任何 matplotlib.patches.FancyArrowPatch中的关键字 |

如果设置了’arrowstyle’关键字,以上关键字就不能使用。允许的值有:

箭头的样式 属性
'-' None
'->' head_length=0.4,head_width=0.2
'-[' widthB=1.0,lengthB=0.2,angleB=None
`’ - ‘` widthA=1.0,widthB=1.0
`’- >’` head_length=0.4,head_width=0.2
'<-' head_length=0.4,head_width=0.2
'<->' head_length=0.4,head_width=0.2
`’< -‘` head_length=0.4,head_width=0.2
`’< - >’` head_length=0.4,head_width=0.2
'fancy' head_length=0.4,head_width=0.4,tail_width=0.4
'simple' head_length=0.5,head_width=0.5,tail_width=0.2
'wedge' tail_width=0.3,shrink_factor=0.5

下图展现了不同的arrowstyle的不同形式
数据可视化笔记task04——文字图例尽眉目 - 图3

  • FancyArrowPatch的关键字包括: | Key | Description | | :—-: | :—-: | | arrowstyle | 箭头的样式 | | connectionstyle | 连接线的样式 | | relpos | 箭头起始点相对注释文本的位置,默认为 (0.5, 0.5),即文本的中心,(0,0)表示左下角,(1,1)表示右上角 | | patchA | 箭头起点处的图形(matplotlib.patches对象),默认是注释文字框 | | patchB | 箭头终点处的图形(matplotlib.patches对象),默认为空 | | shrinkA | 箭头起点的缩进点数,默认为2 | | shrinkB | 箭头终点的缩进点数,默认为2 | | mutation_scale | default is text size (in points) | | mutation_aspect | default is 1. | | ? | any key for matplotlib.patches.PathPatch |
  • annotation_clip : 布尔值,可选参数,默认为空。设为True时,只有被注释点在axes时才绘制注释;设为False时,无论被注释点在哪里都绘制注释。仅当xycoords为‘data’时,默认值空相当于True。


  • **kwargs:该参数接受任何Text的参数


  1. #此代码主要给示范了不同的arrowstyle以及FancyArrowPatch的样式
  2. import matplotlib.pyplot as plt
  3. import matplotlib.patches as mpatches
  4. fig, axs = plt.subplots(2, 2)
  5. x1, y1 = 0.3, 0.3
  6. x2, y2 = 0.7, 0.7
  7. ax = axs.flat[0]
  8. ax.plot([x1, x2], [y1, y2], ".")
  9. el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
  10. ax.add_artist(el)#在axes中创建一个artist
  11. ax.annotate("",
  12. xy=(x1, y1), xycoords='data',
  13. xytext=(x2, y2), textcoords='data',
  14. arrowprops=dict(arrowstyle="-",#箭头的样式
  15. color="0.5",
  16. patchB=None,
  17. shrinkB=0,
  18. connectionstyle="arc3,rad=0.3",
  19. ),
  20. )
  21. #在整个代码中使用Transform=ax.transAx表示坐标相对于axes的bounding box,其中(0,0)是轴的左下角,(1,1)是右上角。
  22. ax.text(.05, .95, "connect", transform=ax.transAxes, ha="left", va="top")
  23. ax = axs.flat[1]
  24. ax.plot([x1, x2], [y1, y2], ".")
  25. el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
  26. ax.add_artist(el)
  27. ax.annotate("",
  28. xy=(x1, y1), xycoords='data',
  29. xytext=(x2, y2), textcoords='data',
  30. arrowprops=dict(arrowstyle="-",
  31. color="0.5",
  32. patchB=el,#箭头终点处的图形
  33. shrinkB=0,
  34. connectionstyle="arc3,rad=0.3",
  35. ),
  36. )
  37. ax.text(.05, .95, "clip", transform=ax.transAxes, ha="left", va="top")
  38. ax = axs.flat[2]
  39. ax.plot([x1, x2], [y1, y2], ".")
  40. el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
  41. ax.add_artist(el)
  42. ax.annotate("",
  43. xy=(x1, y1), xycoords='data',
  44. xytext=(x2, y2), textcoords='data',
  45. arrowprops=dict(arrowstyle="-",
  46. color="0.5",
  47. patchB=el,
  48. shrinkB=5,
  49. connectionstyle="arc3,rad=0.3",
  50. ),
  51. )
  52. ax.text(.05, .95, "shrink", transform=ax.transAxes, ha="left", va="top")
  53. ax = axs.flat[3]
  54. ax.plot([x1, x2], [y1, y2], ".")
  55. el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
  56. ax.add_artist(el)
  57. ax.annotate("",
  58. xy=(x1, y1), xycoords='data',
  59. xytext=(x2, y2), textcoords='data',
  60. arrowprops=dict(arrowstyle="fancy",
  61. color="0.5",
  62. patchB=el,
  63. shrinkB=5,#箭头终点的缩进点数
  64. connectionstyle="arc3,rad=0.3",
  65. ),
  66. )
  67. ax.text(.05, .95, "mutate", transform=ax.transAxes, ha="left", va="top")
  68. for ax in axs.flat:
  69. ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
  70. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图4

两个点之间的连接路径主要有connectionstyle和以下样式确定

Name Attrs
angle angleA=90,angleB=0,rad=0.0
angle3 angleA=90,angleB=0
arc angleA=0,angleB=0,armA=None,armB=None,rad=0.0
arc3 rad=0.0
bar armA=0.0,armB=0.0,fraction=0.3,angle=None

其中angle3 和 arc3 中的 3 意味着所得到的路径是二次样条段( 三个控制点)

下面的例子丰富的展现了连接线的用法,可以参考学习

例子1:

  1. import matplotlib.pyplot as plt
  2. def demo_con_style(ax, connectionstyle):
  3. x1, y1 = 0.3, 0.2
  4. x2, y2 = 0.8, 0.6
  5. ax.plot([x1, x2], [y1, y2], ".")
  6. ax.annotate("",
  7. xy=(x1, y1), xycoords='data',
  8. xytext=(x2, y2), textcoords='data',
  9. arrowprops=dict(arrowstyle="->", color="0.5",
  10. shrinkA=5, shrinkB=5,
  11. patchA=None, patchB=None,
  12. connectionstyle=connectionstyle,
  13. ),
  14. )
  15. ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
  16. transform=ax.transAxes, ha="left", va="top")
  17. fig, axs = plt.subplots(3, 5, figsize=(8, 4.8))
  18. demo_con_style(axs[0, 0], "angle3,angleA=90,angleB=0")
  19. demo_con_style(axs[1, 0], "angle3,angleA=0,angleB=90")
  20. demo_con_style(axs[0, 1], "arc3,rad=0.")
  21. demo_con_style(axs[1, 1], "arc3,rad=0.3")
  22. demo_con_style(axs[2, 1], "arc3,rad=-0.3")
  23. demo_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0")
  24. demo_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5")
  25. demo_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5")
  26. demo_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0")
  27. demo_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5")
  28. demo_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
  29. demo_con_style(axs[0, 4], "bar,fraction=0.3")
  30. demo_con_style(axs[1, 4], "bar,fraction=-0.3")
  31. demo_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")
  32. for ax in axs.flat:
  33. ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
  34. fig.tight_layout(pad=0.2)
  35. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图5

例子2:

  1. #以下两个block懂了之后,annotate基本懂了
  2. #如果想更深入学习可以参看官网案例学习https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.annotate.html#matplotlib.axes.Axes.annotate
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # 以步长0.005绘制一个曲线
  6. x = np.arange(0, 10, 0.005)
  7. y = np.exp(-x/2.) * np.sin(2*np.pi*x)
  8. fig, ax = plt.subplots()
  9. ax.plot(x, y)
  10. ax.set_xlim(0, 10)#设置x轴的范围
  11. ax.set_ylim(-1, 1)#设置x轴的范围
  12. # 被注释点的数据轴坐标和所在的像素
  13. xdata, ydata = 5, 0
  14. xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))
  15. # 设置注释文本的样式和箭头的样式
  16. bbox = dict(boxstyle="round", fc="0.8")
  17. arrowprops = dict(
  18. arrowstyle = "->",
  19. connectionstyle = "angle,angleA=0,angleB=90,rad=10")
  20. # 设置偏移量
  21. offset = 72
  22. # xycoords默认为'data'数据轴坐标,对坐标点(5,0)添加注释
  23. # 注释文本参考被注释点设置偏移量,向左2*72points,向上72points
  24. ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata),
  25. (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',
  26. bbox=bbox, arrowprops=arrowprops)
  27. # xycoords以绘图区左下角为参考,单位为像素
  28. # 注释文本参考被注释点设置偏移量,向右0.5*72points,向下72points
  29. disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay),
  30. (xdisplay, ydisplay), xytext=(0.5*offset, -offset),
  31. xycoords='figure pixels',
  32. textcoords='offset points',
  33. bbox=bbox, arrowprops=arrowprops)
  34. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图6

例子3:

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # 绘制一个极地坐标,再以0.001为步长,画一条螺旋曲线
  4. fig = plt.figure()
  5. ax = fig.add_subplot(111, polar=True)
  6. r = np.arange(0,1,0.001)
  7. theta = 2 * 2*np.pi * r
  8. line, = ax.plot(theta, r, color='#ee8d18', lw=3)
  9. # 对索引为800处画一个圆点,并做注释
  10. ind = 800
  11. thisr, thistheta = r[ind], theta[ind]
  12. ax.plot([thistheta], [thisr], 'o')
  13. ax.annotate('a polar annotation',
  14. xy=(thistheta, thisr), # 被注释点遵循极坐标系,坐标为角度和半径
  15. xytext=(0.05, 0.05), # 注释文本放在绘图区的0.05百分比处
  16. textcoords='figure fraction',
  17. arrowprops=dict(facecolor='black', shrink=0.05),# 箭头线为黑色,两端缩进5%
  18. horizontalalignment='left',# 注释文本的左端和低端对齐到指定位置
  19. verticalalignment='bottom',
  20. )
  21. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图7

1.7 字体的属性设置

字体设置一般有全局字体设置和自定义局部字体设置两种方法。

  1. #首先可以查看matplotlib所有可用的字体
  2. from matplotlib import font_manager
  3. font_family = font_manager.fontManager.ttflist
  4. font_name_list = [i.name for i in font_family]
  5. for font in font_name_list:
  6. print(f'{font}\n')
  1. STIXNonUnicode
  2. DejaVu Sans Mono
  3. cmtt10
  4. cmmi10
  5. cmss10
  6. cmr10
  7. STIXSizeOneSym
  8. STIXSizeFiveSym
  9. cmb10
  10. DejaVu Sans
  11. STIXSizeFourSym
  12. DejaVu Serif Display
  13. DejaVu Sans Display
  14. STIXSizeThreeSym
  15. DejaVu Sans Mono
  16. STIXGeneral
  17. cmex10
  18. DejaVu Sans
  19. DejaVu Sans
  20. STIXGeneral
  21. STIXSizeThreeSym
  22. STIXSizeTwoSym
  23. DejaVu Sans
  24. STIXNonUnicode
  25. STIXSizeOneSym
  26. cmsy10
  27. DejaVu Sans Mono
  28. STIXGeneral
  29. STIXNonUnicode
  30. STIXNonUnicode
  31. DejaVu Sans Mono
  32. DejaVu Serif
  33. STIXSizeFourSym
  34. DejaVu Serif
  35. STIXGeneral
  36. STIXSizeTwoSym
  37. DejaVu Serif
  38. DejaVu Serif
  39. DilleniaUPC
  40. Arial
  41. Courier New
  42. Calibri
  43. Utsaah
  44. Aparajita
  45. Kalinga
  46. Futura Md BT
  47. IrisUPC
  48. Tahoma
  49. NewsGoth Lt BT
  50. Geometr706 BlkCn BT
  51. Arial
  52. DilleniaUPC
  53. Kokila
  54. Georgia
  55. Cordia New
  56. LilyUPC
  57. Comic Sans MS
  58. NewsGoth BT
  59. CentSchbkCyrill BT
  60. Palatino Linotype
  61. CentSchbkCyrill BT
  62. Kartika
  63. Raavi
  64. Agency FB
  65. Century751 SeBd BT
  66. Utsaah
  67. Corbel
  68. MingLiU-ExtB
  69. Segoe Script
  70. EucrosiaUPC
  71. EngraversGothic BT
  72. Plantagenet Cherokee
  73. Swis721 BT
  74. Courier New
  75. Humnst777 Lt BT
  76. DFPOP1-W9
  77. Agency FB
  78. BrowalliaUPC
  79. Swis721 Cn BT
  80. Bodoni Bd BT
  81. Traditional Arabic
  82. Century751 SeBd BT
  83. Microsoft PhagsPa
  84. Candara
  85. GeoSlab703 Md BT
  86. AngsanaUPC
  87. Futura Bk BT
  88. KodchiangUPC
  89. GeoSlab703 MdCn BT
  90. Microsoft YaHei
  91. FreesiaUPC
  92. BrowalliaUPC
  93. Mangal
  94. Geometr212 BkCn BT
  95. AngsanaUPC
  96. Alibaba PuHuiTi
  97. Humnst777 Cn BT
  98. Futura Bk BT
  99. Microsoft Uighur
  100. Shruti
  101. Consolas
  102. Meiryo
  103. Microsoft YaHei
  104. Lao UI
  105. Swis721 BT
  106. Nyala
  107. Humanst521 BT
  108. Swis721 Hv BT
  109. Arial
  110. Microsoft Tai Le
  111. Swis721 BT
  112. Courier New
  113. Clarendon Lt BT
  114. Kaufmann BT
  115. Kokila
  116. Square721 Cn BT
  117. Constantia
  118. MingLiU
  119. Arial
  120. Kalinga
  121. Malgun Gothic
  122. Browallia New
  123. Angsana New
  124. CentSchbkCyrill BT
  125. Euphemia
  126. Browallia New
  127. ISOCPEUR
  128. MS Mincho
  129. DaunPenh
  130. KaiTi
  131. Rod
  132. Clarendon BT
  133. Latha
  134. Andalus
  135. Angsana New
  136. CordiaUPC
  137. Vani
  138. FreesiaUPC
  139. Batang
  140. Kokila
  141. Candara
  142. Candara
  143. NewsGoth BT
  144. Constantia
  145. Verdana
  146. AngsanaUPC
  147. Gautami
  148. Georgia
  149. Swis721 Cn BT
  150. Aparajita
  151. Alibaba PuHuiTi
  152. Aparajita
  153. JasmineUPC
  154. Century751 No2 BT
  155. Consolas
  156. DeVinne Txt BT
  157. NewsGoth Cn BT
  158. Century751 BT
  159. Lucida Sans Unicode
  160. Kartika
  161. Segoe Print
  162. KodchiangUPC
  163. Simplified Arabic
  164. Humnst777 Cn BT
  165. Sakkal Majalla
  166. Sylfaen
  167. Tunga
  168. Microsoft Tai Le
  169. Lucida Console
  170. Lato
  171. Microsoft PhagsPa
  172. Lao UI
  173. Swis721 BT
  174. GeoSlab703 Md BT
  175. Embassy BT
  176. OCR-B 10 BT
  177. IrisUPC
  178. News701 BT
  179. Segoe Print
  180. KodchiangUPC
  181. KodchiangUPC
  182. Meiryo
  183. Microsoft Himalaya
  184. Century751 No2 BT
  185. Bodoni Bk BT
  186. Segoe UI
  187. Times New Roman
  188. Square721 BT
  189. Marlett
  190. Wingdings
  191. ClassInFont
  192. Futura Md BT
  193. Franklin Gothic Medium
  194. Courier New
  195. Humnst777 BlkCn BT
  196. Vijaya
  197. DokChampa
  198. Calibri
  199. Corbel
  200. EucrosiaUPC
  201. SimHei
  202. LilyUPC
  203. Alibaba PuHuiTi
  204. Bodoni Bk BT
  205. IrisUPC
  206. GeoSlab703 MdCn BT
  207. Mongolian Baiti
  208. Traditional Arabic
  209. JasmineUPC
  210. Humanst521 BT
  211. Leelawadee
  212. Verdana
  213. DFMincho-SU
  214. Tunga
  215. Times New Roman
  216. icomoon
  217. Georgia
  218. Microsoft JhengHei
  219. HelvLight
  220. Vrinda
  221. News706 BT
  222. Trebuchet MS
  223. AngsanaUPC
  224. Symbol
  225. News701 BT
  226. Segoe UI Symbol
  227. Constantia
  228. DFGothic-EB
  229. Aharoni
  230. Utsaah
  231. Century751 BT
  232. Levenim MT
  233. CordiaUPC
  234. Calibri
  235. Swis721 Blk BT
  236. Exotc350 DmBd BT
  237. Humanst521 BT
  238. Shonar Bangla
  239. MoolBoran
  240. Calibri
  241. Cambria
  242. Consolas
  243. Browallia New
  244. MT Extra
  245. Segoe Script
  246. DFKaiSho-SB
  247. Angsana New
  248. Microsoft JhengHei
  249. Bodoni Bd BT
  250. Microsoft New Tai Lue
  251. Impact
  252. Humnst777 BT
  253. Segoe UI
  254. NewsGoth BT
  255. Swis721 LtEx BT
  256. Shruti
  257. Freehand521 BT
  258. Clarendon BT
  259. MS Gothic
  260. Times New Roman
  261. Palatino Linotype
  262. Microsoft Yi Baiti
  263. Century751 No2 BT
  264. BrowalliaUPC
  265. Century751 No2 BT
  266. CordiaUPC
  267. Candara
  268. GeoSlab703 Md BT
  269. Open Sans
  270. Kokila
  271. CordiaUPC
  272. Cordia New
  273. Segoe UI
  274. Gautami
  275. Mangal
  276. Vijaya
  277. Palatino Linotype
  278. Swis721 Lt BT
  279. Angsana New
  280. JasmineUPC
  281. FangSong
  282. Swis721 WGL4 BT
  283. FrankRuehl
  284. DFMincho-UB
  285. Khmer UI
  286. Exotc350 Bd BT
  287. Calibri
  288. Levenim MT
  289. CentSchbkCyrill BT
  290. Calibri
  291. Cordia New
  292. Geometr415 Blk BT
  293. Narkisim
  294. Swis721 WGL4 BT
  295. Verdana
  296. Cambria
  297. Corbel
  298. Malgun Gothic
  299. Swis721 Cn BT
  300. Arabic Typesetting
  301. BrowalliaUPC
  302. NewsGoth BT
  303. Ebrima
  304. Gabriola
  305. Khmer UI
  306. Palatino Linotype
  307. Futura Md BT
  308. LilyUPC
  309. Cambria
  310. TypoUpright BT
  311. FZLanTingHei-H-GBK
  312. DilleniaUPC
  313. Cambria
  314. Miriam
  315. OCR-A BT
  316. Futura Md BT
  317. Franklin Gothic Medium
  318. Schadow BT
  319. Estrangelo Edessa
  320. Constantia
  321. Swis721 Lt BT
  322. Segoe UI
  323. Humanst521 Lt BT
  324. Leelawadee
  325. Clarendon Blk BT
  326. FreesiaUPC
  327. Comic Sans MS
  328. Webdings
  329. SimSun-ExtB
  330. Humanst521 Lt BT
  331. JasmineUPC
  332. Consolas
  333. Vrinda
  334. Tahoma
  335. Corbel
  336. Times New Roman
  337. Utsaah
  338. Arial
  339. Geometr212 BkCn BT
  340. Aparajita
  341. Square721 BT
  342. Browallia New
  343. FreesiaUPC
  344. Trebuchet MS
  345. GeoSlab703 Md BT
  346. Gulim
  347. SimSun
  348. Open Sans
  349. DFMincho-W5
  350. Humanst521 BT
  351. Raavi
  352. LilyUPC
  353. Ebrima
  354. Georgia
  355. Square721 Cn BT
  356. Microsoft New Tai Lue
  357. EucrosiaUPC
  358. MV Boli
  359. Shonar Bangla
  360. Alibaba PuHuiTi
  361. Latha
  362. Gisha
  363. DFKai-SB
  364. Humnst777 Blk BT
  365. Sakkal Majalla
  366. David
  367. Swis721 BlkCn BT
  368. Century725 Cn BT
  369. IrisUPC
  370. Swis721 WGL4 BT
  371. Swis721 Cn BT
  372. EucrosiaUPC
  373. Simplified Arabic
  374. Simplified Arabic Fixed
  375. Source Han Sans CN
  376. Miriam Fixed
  377. Segoe UI
  378. Iskoola Pota
  379. Vani
  380. Trebuchet MS
  381. Segoe UI
  382. DilleniaUPC
  383. Gisha
  384. Microsoft Sans Serif
  385. Verdana
  386. UNAVAILABLE
  387. Trebuchet MS
  388. Schadow BT
  389. Alibaba PuHuiTi
  390. Cordia New
  391. Swis721 WGL4 BT
  392. Iskoola Pota
  393. David


为方便在图中加入合适的字体,可以尝试了解中文字体的英文名称,该链接告诉了常用中文的英文名称

  1. #该block讲述如何在matplotlib里面,修改字体默认属性,完成全局字体的更改。
  2. import matplotlib.pyplot as plt
  3. plt.rcParams['font.sans-serif'] = ['SimSun'] # 指定默认字体为新宋体。
  4. plt.rcParams['axes.unicode_minus'] = False # 解决保存图像时 负号'-' 显示为方块和报错的问题。

局部字体的修改方法1

  1. import matplotlib.pyplot as plt
  2. import matplotlib.font_manager as fontmg
  3. x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  4. plt.plot(x, label='小示例图标签')
  5. # 直接用字体的名字。
  6. plt.xlabel('x 轴名称参数', fontproperties='Microsoft YaHei', fontsize=16) # 设置x轴名称,采用微软雅黑字体
  7. plt.ylabel('y 轴名称参数', fontproperties='Microsoft YaHei', fontsize=14) # 设置Y轴名称
  8. plt.title('坐标系的标题', fontproperties='Microsoft YaHei', fontsize=20) # 设置坐标系标题的字体
  9. plt.legend(loc='lower right', prop={"family": 'Microsoft YaHei'}, fontsize=10) # 小示例图的字体设置
  10. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图8

局部字体的修改方法2

  1. import matplotlib.pyplot as plt
  2. import matplotlib.font_manager as fontmg
  3. x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  4. plt.plot(x, label='小示例图标签')
  5. #fname为你系统中的字体库路径
  6. my_font1 = fontmg.FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf') # 读取系统中的 黑体 字体。
  7. my_font2 = fontmg.FontProperties(fname=r'C:\Windows\Fonts\simkai.ttf') # 读取系统中的 楷体 字体。
  8. # fontproperties 设置中文显示,fontsize 设置字体大小
  9. plt.xlabel('x 轴名称参数', fontproperties=my_font1, fontsize=16) # 设置x轴名称
  10. plt.ylabel('y 轴名称参数', fontproperties=my_font1, fontsize=14) # 设置Y轴名称
  11. plt.title('坐标系的标题', fontproperties=my_font2, fontsize=20) # 标题的字体设置
  12. plt.legend(loc='lower right', prop=my_font1, fontsize=10) # 小示例图的字体设置
  13. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图9


1.8 数学表达式

在文本标签中使用数学表达式。有关MathText的概述,请参见 写数学表达式,但由于数学表达式的练习想必我们都在markdown语法和latex语法中多少有接触,故在此不继续展开,愿意深入学习的可以参看官方文档。

下面是一个官方案例,供参考了解。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. t = np.arange(0.0, 2.0, 0.01)
  4. s = np.sin(2*np.pi*t)
  5. plt.plot(t, s)
  6. plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
  7. plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
  8. plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
  9. fontsize=20)
  10. plt.xlabel('time (s)')
  11. plt.ylabel('volts (mV)')
  12. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图10


以下是对前七节学习内容的总结案例:

  1. import matplotlib
  2. import matplotlib.pyplot as plt
  3. fig = plt.figure()
  4. ax = fig.add_subplot(111)
  5. fig.subplots_adjust(top=0.85)
  6. # 分别在figure和subplot上设置title
  7. fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
  8. ax.set_title('axes title')
  9. ax.set_xlabel('xlabel')
  10. ax.set_ylabel('ylabel')
  11. # 设置x-axis和y-axis的范围都是[0, 10]
  12. ax.axis([0, 10, 0, 10])
  13. ax.text(3, 8, 'boxed italics text in data coords', style='italic',
  14. bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
  15. ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
  16. font1 = {'family': 'Times New Roman',
  17. 'color': 'purple',
  18. 'weight': 'normal',
  19. 'size': 10,
  20. }
  21. ax.text(3, 2, 'unicode: Institut für Festkörperphysik',fontdict=font1)
  22. ax.text(0.95, 0.01, 'colored text in axes coords',
  23. verticalalignment='bottom', horizontalalignment='right',
  24. transform=ax.transAxes,
  25. color='green', fontsize=15)
  26. ax.plot([2], [1], 'o')
  27. ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
  28. arrowprops=dict(facecolor='black', shrink=0.05))
  29. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图11


2. Tick上的文本

设置tick(刻度)和ticklabel(刻度标签)也是可视化中经常需要操作的步骤,matplotlib既提供了自动生成刻度和刻度标签的模式(默认状态),同时也提供了许多让使用者灵活设置的方式。

2.1 简单模式

可以使用axis的set_ticks方法手动设置标签位置,使用axis的set_ticklabels方法手动设置标签格式

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import matplotlib
  4. x1 = np.linspace(0.0, 5.0, 100)
  5. y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)


使用axis的set_ticks方法手动设置标签位置

  1. # 该案例中由于tick设置过大,所以会影响绘图美观,不建议用此方式进行设置tick
  2. fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
  3. axs[0].plot(x1, y1)
  4. axs[1].plot(x1, y1)
  5. axs[1].xaxis.set_ticks(np.arange(0., 10.1, 2.))
  6. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图12

使用axis的set_ticklabels方法手动设置标签格式

  1. fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
  2. axs[0].plot(x1, y1)
  3. axs[1].plot(x1, y1)
  4. ticks = np.arange(0., 8.1, 2.)
  5. tickla = [f'{tick:1.2f}' for tick in ticks]
  6. axs[1].xaxis.set_ticks(ticks)
  7. axs[1].xaxis.set_ticklabels(tickla)
  8. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图13


修改刻度标签上的文字

  1. #一般绘图时会自动创建刻度,而如果通过上面的例子使用set_ticks创建刻度可能会导致tick的范围与所绘制图形的范围不一致的问题。
  2. #所以在下面的案例中,axs[1]中set_xtick的设置要与数据范围所对应,然后再通过set_xticklabels设置刻度所对应的标签
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. fig, axs = plt.subplots(2, 1, figsize=(6, 4), tight_layout=True)
  6. x1 = np.linspace(0.0, 6.0, 100)
  7. y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
  8. axs[0].plot(x1, y1)
  9. axs[0].set_xticks([0,1,2,3,4,5,6])
  10. axs[1].plot(x1, y1)
  11. axs[1].set_xticks([0,1,2,3,4,5,6])#要将x轴的刻度放在数据范围中的哪些位置
  12. axs[1].set_xticklabels(['zero','one', 'two', 'three', 'four', 'five','six'], # 设置刻度对应的标签
  13. rotation=30, fontsize='small') # rotation选项设定x刻度标签倾斜30度。
  14. axs[1].xaxis.set_ticks_position('bottom') # set_ticks_position()方法是用来设置刻度所在的位置,常用的参数有bottom、top、both、none
  15. print(axs[1].xaxis.get_ticklines())
  16. plt.show()


数据可视化笔记task04——文字图例尽眉目 - 图14


2.2 Tick Locators and Formatters

除了上述的简单模式,还可以使用Tick Locators and Formatters完成对于刻度位置和刻度标签的设置。
其中:

这种方式的好处是不用显式地列举出刻度值列表。

set_major_formatterset_minor_formatter这两个formatter格式命令可以接收字符串格式(matplotlib.ticker.StrMethodFormatter)或函数参数(matplotlib.ticker.FuncFormatter)来设置刻度值的格式 。

2.2.1 Tick Formatters

  1. # 接收字符串格式的例子
  2. fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
  3. for n, ax in enumerate(axs.flat):
  4. ax.plot(x1*10., y1)
  5. formatter = matplotlib.ticker.FormatStrFormatter('%1.1f')
  6. axs[0, 1].xaxis.set_major_formatter(formatter)
  7. formatter = matplotlib.ticker.FormatStrFormatter('-%1.1f')
  8. axs[1, 0].xaxis.set_major_formatter(formatter)
  9. formatter = matplotlib.ticker.FormatStrFormatter('%1.5f')
  10. axs[1, 1].xaxis.set_major_formatter(formatter)
  11. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图15

  1. # 接收函数的例子
  2. def formatoddticks(x, pos):
  3. """Format odd tick positions."""
  4. if x % 2:
  5. return f'{x:1.2f}'
  6. else:
  7. return ''
  8. fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
  9. ax.plot(x1, y1)
  10. ax.xaxis.set_major_formatter(formatoddticks)
  11. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图16


2.2.2 Tick Locators

在普通的绘图中,我们可以直接通过上图的set_ticks进行设置刻度的位置,缺点是需要自己指定或者接受matplotlib默认给定的刻度。当需要更改刻度的位置时,matplotlib给了常用的几种locator的类型。如果要绘制更复杂的图,可以先设置locator的类型,然后通过axs.xaxis.set_major_locator(locator) 绘制即可

  • locator=plt.MaxNLocator(nbins=7)
  • locator=plt.FixedLocator(locs=[0,0.5,1.5,2.5,3.5,4.5,5.5,6]) # 直接指定刻度所在的位置
  • locator=plt.AutoLocator() # 自动分配刻度值的位置
  • locator=plt.IndexLocator(offset=0.5, base=1) # 面元间距是1,从0.5开始
  • locator=plt.MultipleLocator(1.5) # 将刻度的标签设置为1.5的倍数
  • locator=plt.LinearLocator(numticks=5) # 线性划分5等分,4个刻度
    1. # 接收各种locator的例子
    2. fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
    3. for n, ax in enumerate(axs.flat):
    4. ax.plot(x1*10., y1)
    5. locator = matplotlib.ticker.AutoLocator()
    6. axs[0, 0].xaxis.set_major_locator(locator)
    7. locator = matplotlib.ticker.MaxNLocator(nbins=10)
    8. axs[0, 1].xaxis.set_major_locator(locator)
    9. locator = matplotlib.ticker.MultipleLocator(5)
    10. axs[1, 0].xaxis.set_major_locator(locator)
    11. locator = matplotlib.ticker.FixedLocator([0,7,14,21,28])
    12. axs[1, 1].xaxis.set_major_locator(locator)
    13. plt.show()
    数据可视化笔记task04——文字图例尽眉目 - 图17


此外matplotlib.dates 模块还提供了特殊的设置日期型刻度格式和位置的方式

  1. import matplotlib.dates as mdates
  2. import datetime
  3. # 特殊的日期型locator和formatter
  4. locator = mdates.DayLocator(bymonthday=[1,15,25])
  5. formatter = mdates.DateFormatter('%b %d')
  6. fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
  7. ax.xaxis.set_major_locator(locator)
  8. ax.xaxis.set_major_formatter(formatter)
  9. base = datetime.datetime(2017, 1, 1, 0, 0, 1)
  10. time = [base + datetime.timedelta(days=x) for x in range(len(x1))]
  11. ax.plot(time, y1)
  12. ax.tick_params(axis='x', rotation=70)
  13. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图18


其他案例

  1. #这个案例中展示了如何进行坐标轴的移动,如何更改刻度值的样式
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. x = np.linspace(-3,3,50)
  5. y1 = 2*x+1
  6. y2 = x**2
  7. plt.figure()
  8. plt.plot(x,y2)
  9. plt.plot(x,y1,color='red',linewidth=1.0,linestyle = '--')
  10. plt.xlim((-3,5))
  11. plt.ylim((-3,5))
  12. plt.xlabel('x')
  13. plt.ylabel('y')
  14. new_ticks1 = np.linspace(-3,5,5)
  15. plt.xticks(new_ticks1)
  16. plt.yticks([-2,0,2,5],[r'$one\ shu$',r'$\alpha$',r'$three$',r'four'])
  17. '''
  18. 上一行代码是将y轴上的小标改成文字,其中,空格需要增加\,即'\ ',$可将格式更改成数字模式,如果需要输入数学形式的α,则需要用\转换,即\alpha
  19. 如果使用面向对象的命令进行画图,那么下面两行代码可以实现与 plt.yticks([-2,0,2,5],[r'$one\ shu$',r'$\alpha$',r'$three$',r'four']) 同样的功能
  20. axs.set_yticks([-2,0,2,5])
  21. axs.set_yticklabels([r'$one\ shu$',r'$\alpha$',r'$three$',r'four'])
  22. '''
  23. ax = plt.gca()#gca = 'get current axes' 获取现在的轴
  24. '''
  25. ax = plt.gca()是获取当前的axes,其中gca代表的是get current axes。
  26. fig=plt.gcf是获取当前的figure,其中gcf代表的是get current figure。
  27. 许多函数都是对当前的Figure或Axes对象进行处理,
  28. 例如plt.plot()实际上会通过plt.gca()获得当前的Axes对象ax,然后再调用ax.plot()方法实现真正的绘图。
  29. 而在本例中则可以通过ax.spines方法获得当前顶部和右边的轴并将其颜色设置为不可见
  30. 然后将左边轴和底部的轴所在的位置重新设置
  31. 最后再通过set_ticks_position方法设置ticks在x轴或y轴的位置,本示例中因所设置的bottom和left是ticks在x轴或y轴的默认值,所以这两行的代码也可以不写
  32. '''
  33. ax.spines['top'].set_color('none')
  34. ax.spines['right'].set_color('none')
  35. ax.spines['left'].set_position(('data',0))
  36. ax.spines['bottom'].set_position(('data',0)) # axes 百分比
  37. ax.xaxis.set_ticks_position('bottom') # 设置ticks在x轴的位置
  38. ax.yaxis.set_ticks_position('left') # 设置ticks在y轴的位置
  39. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图19


3. legend(图例)

图例的设置会使用一些常见术语,为了清楚起见,这些术语在此处进行说明:

  • legend entry(图例条目)

图例有一个或多个legend entries组成。一个entry由一个key和一个label组成。

  • legend key(图例键)

每个 legend label左面的colored/patterned marker(彩色/图案标记)

  • legend label(图例标签)

描述由key来表示的handle的文本

  • legend handle(图例句柄)

用于在图例中生成适当图例条目的原始对象

以下面这个图为例,右侧的方框中的共有两个legend entry;两个legend key,分别是一个蓝色和一个黄色的legend key;两个legend label,一个名为 ‘Line up’ 和一个名为’Line Down’ 的legend label
image.png

语法:
matplotlib.pyplot.legend(*args, **kwargs)

参数:此方法接受以下描述的参数:

keyword Description
loc Location code string, or tuple (see below).图例所有figure位置
prop the font property字体参数
fontsize the font size (used only if prop is not specified)
markerscale the relative size of legend markers vs. original图例标记与原始标记的相对大小
markerfirst If True (default), marker is to left of the label.如果为True,则图例标记位于图例标签的左侧
numpoints the number of points in the legend for line为线条图图例条目创建的标记点数
scatterpoints the number of points in the legend for scatter plot为散点图图例条目创建的标记点数
scatteryoffsets a list of yoffsets for scatter symbols in legend为散点图图例条目创建的标记的垂直偏移量
frameon If True, draw the legend on a patch (frame).控制是否应在图例周围绘制框架
fancybox If True, draw the frame with a round fancybox.控制是否应在构成图例背景的FancyBboxPatch周围启用圆边
shadow If True, draw a shadow behind legend.控制是否在图例后面画一个阴
framealpha Transparency of the frame.控制图例框架的 Alpha 透明度
edgecolor Frame edgecolor.
facecolor Frame facecolor.
ncol number of columns 设置图例分为n列展示
borderpad the fractional whitespace inside the legend border图例边框的内边距
labelspacing the vertical space between the legend entries图例条目之间的垂直间距
handlelength the length of the legend handles 图例句柄的长度
handleheight the height of the legend handles 图例句柄的高度
handletextpad the pad between the legend handle and text 图例句柄和文本之间的间距
borderaxespad the pad between the axes and legend border轴与图例边框之间的距离
columnspacing the spacing between columns 列间距
title the legend title
bbox_to_anchor the bbox that the legend will be anchored.指定图例在轴的位置
bbox_transform the transform for the bbox. transAxes if None.


常用的几个参数:
(1)设置图列位置
plt.legend(loc='upper center') 等同于plt.legend(loc=9)
以下数字和对应字符串是相等的效果的。

数字 字符串
0 ‘best’
1 ‘upper right’
2 ‘upper left’
3 ‘lower left’
4 ‘lower right’
5 ‘right’
6 ‘center left’
7 ‘center right’
8 ‘lower center’
9 ‘upper center’
10 ‘center’

(2)设置图例字体大小
fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

(3)设置图例边框及背景
plt.legend(loc=’best’,frameon=False) #去掉图例边框
plt.legend(loc=’best’,edgecolor=’blue’) # 设置图例边框颜色
plt.legend(loc=’best’,facecolor=’blue’) #设置图例背景颜色,若无边框,参数无效

(4)设置图例标题
legend = plt.legend([“CH”, “US”], title=’China VS Us’)

(5)设置图例名字及对应关系
legend = plt.legend([p1, p2], [“CH”, “US”])

第3节开头的图例用以下代码可以实现

  1. line_up, = plt.plot([1, 2, 3], label='Line 2')
  2. line_down, = plt.plot([3, 2, 1], label='Line 1')
  3. #loc参数设置图例所在的位置,title设置图例的标题,frameon参数将图例边框给去掉
  4. plt.legend([line_up, line_down], ['Line Up', 'Line Down'],loc=5, title='line',frameon=False)
  5. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图21

显示多图例legend

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. x = np.random.uniform(-1, 1, 4)
  4. y = np.random.uniform(-1, 1, 4)
  5. p1, = plt.plot([1,2,3])
  6. p2, = plt.plot([3,2,1])
  7. l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')
  8. p3 = plt.scatter(x[0:2], y[0:2], marker = 'D', color='r')
  9. p4 = plt.scatter(x[2:], y[2:], marker = 'D', color='g')
  10. # 下面这行代码由于添加了新的legend,所以会将l1从legend中给移除
  11. plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1)
  12. # 为了保留之前的l1这个legend,所以必须要通过plt.gca()获得当前的axes,然后将l1作为单独的artist
  13. plt.gca().add_artist(l1)
  14. plt.show()

数据可视化笔记task04——文字图例尽眉目 - 图22

4. 作业

4.1

尝试在一张图中运用所讲过的功能,对title、text、xlable、ylabel、数学表达式、tick and ticklabel、legend进行详细的设计。

回答:

  1. import matplotlib.pyplot as plt
  2. import matplotlib
  3. import numpy as np
  4. t = np.arange(-np.pi-0.3, np.pi+0.3, 0.01)
  5. s1 = np.sin(t)
  6. s2 = np.sin(2*t)
  7. fig, ax = plt.subplots(figsize=(8,6))
  8. f1 = ax.plot(t, s1, label=r'$y=\mathrm{sin}(x)$')
  9. f2 = ax.plot(t, s2, label=r'$y=\mathrm{sin}(2x)$')
  10. ax.grid(True, linestyle='-.')
  11. locator = matplotlib.ticker.FixedLocator([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
  12. majorfmt = matplotlib.ticker.FixedFormatter([r'$-{\pi}$', r'$-{\pi}/2$', r'${\pi}/2$', r'${\pi}$'])
  13. ax.xaxis.set_minor_locator(locator)
  14. ax.xaxis.set_minor_formatter(majorfmt)
  15. ax.tick_params(axis='x', which='minor',
  16. length=8, width=2, labelsize=15,
  17. color='red', rotation=0)
  18. ax.spines['top'].set_color('none')
  19. ax.spines['right'].set_color('none')
  20. ax.spines['left'].set_position(('data',0))
  21. ax.spines['bottom'].set_position(('data',0))
  22. ax.xaxis.set_ticks_position('bottom')
  23. ax.yaxis.set_ticks_position('left')
  24. ax.set_xlabel('x',
  25. {'family':'Times New Roman',
  26. 'weight':'normal',
  27. 'size' : 28},
  28. loc='right')
  29. ax.set_ylabel('y',
  30. {'family':'Times New Roman',
  31. 'weight':'normal',
  32. 'size' : 28},
  33. loc='top', rotation=0)
  34. fig.suptitle('Figure of sin(x) and sin(2x)', fontsize=16)
  35. plt.legend(loc='upper right', fontsize=13)
  36. plt.show()

image.png

4.2

阅读你可能用到文献或者相关书籍,思考自己如何才能通过学过的例子将自己认为比较好看的图给复现出来。

参考资料
1.Python学习笔记(4)——Matplotlib中的annotate(注解)的用法