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程序的执行原理
Apr 11 Python
Django中ORM表的创建和增删改查方法示例
Nov 15 Python
Python实现的knn算法示例
Jun 14 Python
Python计算开方、立方、圆周率,精确到小数点后任意位的方法
Jul 17 Python
Python Learning 列表的更多操作及示例代码
Aug 22 Python
Python字符串大小写转换拼接删除空白
Sep 19 Python
python3 写一个WAV音频文件播放器的代码
Sep 27 Python
Python实现计算长方形面积(带参数函数demo)
Jan 18 Python
浅谈matplotlib 绘制梯度下降求解过程
Jul 12 Python
Python faker生成器生成虚拟数据代码实例
Jul 20 Python
python小程序之飘落的银杏
Apr 17 Python
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中的global
2014/08/19 PHP
PHP的switch判断语句的“高级”用法详解
2014/10/01 PHP
PHP+Ajax实现的无刷新分页功能详解【附demo源码下载】
2017/07/03 PHP
PHP基于自定义函数实现的汉字转拼音功能实例
2017/09/30 PHP
PHP基于imagick扩展实现合成图片的两种方法【附imagick扩展下载】
2017/11/14 PHP
PHP7导出Excel报ERR_EMPTY_RESPONSE解决方法
2019/04/16 PHP
JS如何将UTC格式时间转本地格式
2013/09/04 Javascript
jquery数组封装使用方法分享(jquery数组遍历)
2014/03/25 Javascript
基于JQuery实现分隔条的功能
2016/06/17 Javascript
js 模仿锚点定位的实现方法
2016/11/19 Javascript
Vue.js 2.0中select级联下拉框实例
2017/03/06 Javascript
详解vue移动端项目的适配(以mint-ui为例)
2018/08/17 Javascript
jQuery实现购物车的总价计算和总价传值功能
2018/11/28 jQuery
JS执行控制之节流模式实例分析
2018/12/21 Javascript
微信小程序实现通过双向滑动缩放图片大小的方法
2018/12/30 Javascript
详解vue-cli+es6引入es5写的js(两种方法)
2019/04/19 Javascript
微信自定义分享链接信息(标题,图片和内容)实现过程详解
2019/09/04 Javascript
python根据开头和结尾字符串获取中间字符串的方法
2015/03/26 Python
Python简单实现控制电脑的方法
2018/01/22 Python
Python for循环中的陷阱详解
2018/07/13 Python
python+influxdb+shell编写区域网络状况表
2018/07/27 Python
windows下pycharm安装、创建文件、配置默认模板
2018/07/31 Python
Windows下python3.6.4安装教程
2018/07/31 Python
python创建ArcGIS shape文件的实现
2019/12/06 Python
Python中的wordcloud库安装问题及解决方法
2020/05/27 Python
无需压缩软件,用python帮你操作压缩包
2020/08/17 Python
用 python 进行微信好友信息分析
2020/11/28 Python
轻松掌握CSS3中的字体大小单位rem的使用方法
2016/05/24 HTML / CSS
阻止移动设备(手机、pad)浏览器双击放大网页的方法
2014/06/03 HTML / CSS
美国翻新电子产品商店:The Store
2019/10/08 全球购物
三方协议书范本
2014/04/22 职场文书
商务英语专业毕业生求职信
2014/07/06 职场文书
2014年财务工作总结与计划
2014/12/08 职场文书
2015年毕业实习工作总结
2014/12/12 职场文书
85句关于理想的名言警句大全
2019/08/22 职场文书
Vue全家桶入门基础教程
2021/05/14 Vue.js