matplotlib源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)


Posted in Python onFebruary 22, 2021

matplotlib中常用的标题主要三种:窗口标题、图像标题和子图标题。
先通过三个案例简要说明这三类标题的实现。

窗口标题、图像标题,子图标题(仅1个子图)

matplotlib源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'

fig = plt.figure()
plt.plot([1, 2])
# 设置图像标题
plt.suptitle("这是图像标题")
# 设置子图标题
plt.title("这是子图标题")
# 获取默认窗口标题
current_title = fig.canvas.manager.window.windowTitle()
print("默认窗口:",current_title)
# 设置窗口标题方式一
fig.canvas.set_window_title("这是窗口标题")
# 设置窗口标题方式二
fig.canvas.manager.window.setWindowTitle("这是窗口标题")

plt.show()

窗口标题、图像标题、子图标题(多子图)

使用subplot函数实现子图

matplotlib源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'

fig = plt.figure()
plt.subplot(1, 2, 1)
plt.plot([1,2,3,4], [1,4,9,16], "go") 
# 设置子图1标题
plt.title("子图1标题")

plt.subplot(122)
plt.plot([1,2,3,4], [1,4,9,16], "r^") # r^ 表示 红色(red)三角
# 设置子图2标题
plt.title("子图2标题")
# 设置图像标题
plt.suptitle("图像标题")
# 设置窗口标题
#fig.canvas.set_window_title("这是窗口标题")
fig.canvas.manager.window.setWindowTitle("这是窗口标题")

plt.show()

使用subplots函数subplots实现子图

matplotlib源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6,6))
ax[0].plot([1,2,3,4], [1,4,9,16], "go") 
# 设置子图1标题
ax[0].set_title("子图1标题") 
ax[1].plot([1,2,3,4], [1,4,9,16], "r^") 
# 设置子图2标题
ax[1].set_title("子图2标题") 
# 设置图像标题
plt.suptitle("图像标题")
# 设置窗口标题
fig.canvas.manager.window.setWindowTitle("这是窗口标题")

plt.show()

原理分析

通过前面三个案例可知:

窗口标题

设置窗口标题可以用两种方法:
一种是调用figure.canvas对象的set_window_title方法,一种是figure.canvas.manager.window对象的setWindowTitle方法。通过下面源码可知,这两种方法其实是等价的。
因此在日常实现过程中,关键是获取当前图像对象(figure),即案例中的fig。该方法只有一个参数,类型为字符串。
可以通过

通过figure.canvas.manager.window对象的windowTitle方法可以获取窗口标题。

class FigureManagerQT(FigureManagerBase):
  def set_window_title(self, title):
    self.window.setWindowTitle(title)

图像标题

调用plt.suptitle函数即可。根据源码可知,plt.suptitle函数其实是调用了当前figure对象的suptitle方法。

suptitle函数参数

def suptitle(self, t, **kwargs):
    """
    Add a centered title to the figure.

    Parameters
    ----------
    t : str
      The title text.

    x : float, default 0.5
      The x location of the text in figure coordinates.

    y : float, default 0.98
      The y location of the text in figure coordinates.

    horizontalalignment, ha : {'center', 'left', right'}, default: 'center'
      The horizontal alignment of the text relative to (*x*, *y*).

    verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
default: 'top'
      The vertical alignment of the text relative to (*x*, *y*).

    fontsize, size : default: :rc:`figure.titlesize`
      The font size of the text. See `.Text.set_size` for possible
      values.

    fontweight, weight : default: :rc:`figure.titleweight`
      The font weight of the text. See `.Text.set_weight` for possible
      values.

    Returns
    -------
    text
      The `.Text` instance of the title.

    Other Parameters
    ----------------
    fontproperties : None or dict, optional
      A dict of font properties. If *fontproperties* is given the
      default values for font size and weight are taken from the
      `.FontProperties` defaults. :rc:`figure.titlesize` and
      :rc:`figure.titleweight` are ignored in this case.

    **kwargs
      Additional kwargs are `matplotlib.text.Text` properties.

    Examples
    --------
    >>> fig.suptitle('This is the figure title', fontsize=12)
    """

子图标题

  • 使用subplot函数:在所在子图中,使用plt.title函数。
  • 使用subplots函数:使用子图对象调用set_title方法。
  • plt.title函数和axes.set_title方法的参数相同。

注意,在使用subplots函数创建子图时,为什么不能使用plt.title函数设置子图标题呢?
根据title函数的源码可知,title函数其实是通过gca()函数获取子图,然后再调用set_title方法设置标题的。根据实验,在使用subplots函数函数创建多个子图时,plt.gca()只能得到最后一个子图的标题,因此,在某些情况下使用plt.title函数可设置最后一个子图的标题。

plt.title函数和axes.set_title方法源码

def title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs):
  return gca().set_title(
    label, fontdict=fontdict, loc=loc, pad=pad, y=y, **kwargs)
Axes.set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs):
  """
  Set a title for the axes.

  Set one of the three available axes titles. The available titles
  are positioned above the axes in the center, flush with the left
  edge, and flush with the right edge.

  Parameters
  ----------
  label : str
    Text to use for the title

  fontdict : dict
    A dictionary controlling the appearance of the title text,
    the default *fontdict* is::

      {'fontsize': rcParams['axes.titlesize'],
      'fontweight': rcParams['axes.titleweight'],
      'color': rcParams['axes.titlecolor'],
      'verticalalignment': 'baseline',
      'horizontalalignment': loc}

  loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation`
    Which title to set.

  y : float, default: :rc:`axes.titley`
    Vertical axes loation for the title (1.0 is the top). If
    None (the default), y is determined automatically to avoid
    decorators on the axes.

  pad : float, default: :rc:`axes.titlepad`
    The offset of the title from the top of the axes, in points.

  Returns
  -------
  `.Text`
    The matplotlib text instance representing the title

  Other Parameters
  ----------------
  **kwargs : `.Text` properties
    Other keyword arguments are text properties, see `.Text` for a list
    of valid text properties.
  """

plt.gca()实验

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(6,6))
ax[0].plot([1,2,3,4], [1,4,9,16], "go") 
ax[1].plot([1,2,3,4], [1,4,9,16], "r^") 

print(plt.gca())
print(ax[0],ax[1])

结果为

AxesSubplot(0.547727,0.11;0.352273x0.77)
AxesSubplot(0.125,0.11;0.352273x0.77) AxesSubplot(0.547727,0.11;0.352273x0.77)

到此这篇关于matplotlib源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)的文章就介绍到这了,更多相关matplotlib 标题内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python的Template使用指南
Sep 11 Python
python中sets模块的用法实例
Sep 30 Python
Python list操作用法总结
Nov 10 Python
玩转python爬虫之cookie使用方法
Feb 17 Python
python 实现网上商城,转账,存取款等功能的信用卡系统
Jul 15 Python
Python爬虫包 BeautifulSoup  递归抓取实例详解
Jan 28 Python
用pycharm开发django项目示例代码
Oct 24 Python
Python 画出来六维图
Jul 26 Python
django之静态文件 django 2.0 在网页中显示图片的例子
Jul 28 Python
Python字典底层实现原理详解
Dec 18 Python
使用Pandas将inf, nan转化成特定的值
Dec 19 Python
只用50行Python代码爬取网络美女高清图片
Jun 02 Python
python利用后缀表达式实现计算器功能
Feb 22 #Python
Python使用tkinter实现小时钟效果
Feb 22 #Python
Python tkinter实现日期选择器
Feb 22 #Python
Pyside2中嵌入Matplotlib的绘图的实现
Feb 22 #Python
Python实现Excel自动分组合并单元格
Feb 22 #Python
matplotlib绘制正余弦曲线图的实现
Feb 22 #Python
Python使用tkinter制作在线翻译软件
Feb 22 #Python
You might like
使用PHP提取视频网站页面中的FLASH地址的代码
2010/04/17 PHP
php 文件缓存函数
2011/10/08 PHP
php和js如何通过json互相传递数据相关问题探讨
2013/02/26 PHP
关于php支持分块与断点续传文件下载功能代码
2014/05/09 PHP
Yii2增删改查之查询 where参数详细介绍
2016/08/08 PHP
学习ExtJS Column布局
2009/10/08 Javascript
js parsefloat parseint 转换函数
2010/01/21 Javascript
js自定义方法通过隐藏iframe实现文件下载
2013/02/21 Javascript
文本框水印提示效果的简单实现代码
2014/02/22 Javascript
JavaScript实现重置表单(reset)的方法
2015/04/02 Javascript
layer弹出层中H5播放器全屏出错的解决方法
2017/02/21 Javascript
Three.js基础学习之场景对象
2017/09/27 Javascript
代码整洁之道(重构)
2018/10/25 Javascript
浅谈Angular7 项目开发总结
2018/12/19 Javascript
基于vue实现滚动条滚动到指定位置对应位置数字进行tween特效
2019/04/18 Javascript
koa+mongoose实现简单增删改查接口的示例代码
2019/05/13 Javascript
linux下python抓屏实现方法
2015/05/22 Python
Python中格式化format()方法详解
2017/04/01 Python
Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例
2017/11/23 Python
python 输入一个数n,求n个数求乘或求和的实例
2018/11/13 Python
Python利用Xpath选择器爬取京东网商品信息
2020/06/01 Python
在tensorflow实现直接读取网络的参数(weight and bias)的值
2020/06/24 Python
新西兰最大的品牌运动鞋购物网站:Platypus NZ
2017/10/27 全球购物
廉价连衣裙和婚纱礼服在线销售:Tbdress
2019/02/28 全球购物
美国传奇滑手Paul Rodriguez创办的街头滑板品牌:Primitive Skateboarding
2019/10/29 全球购物
影视艺术学院毕业生自荐信
2013/11/13 职场文书
自荐信怎么写呢?
2013/12/09 职场文书
2015自愿离婚协议书范本
2015/01/28 职场文书
酒会开场白大全
2015/06/01 职场文书
飞屋环游记观后感
2015/06/08 职场文书
警示教育片观后感
2015/06/17 职场文书
初婚未育证明样本
2015/06/18 职场文书
2015年库房管理工作总结
2015/10/14 职场文书
22句经典语录:送给优柔寡断和胡思乱想的朋友们
2019/12/13 职场文书
Python Matplotlib库实现画局部图
2021/11/17 Python
Golang 结构体数据集合
2022/04/22 Golang