Python 数据分析——Matplotlib相关知识

Python 数据分析——Matplotlib相关知识

第四章 Matplotlib相关知识 —— 文本图例



前言

Matplotlib 具有广泛的文本支持,包括对数学表达式的支持、对光栅和矢量输出的 truetype 支持、具有任意旋转的换行符分隔文本以及 unicode 支持。(参考链接)
了解Matplotlib对文本的设置,可以更好更清晰地展现图表的内容,也更加容易让旁观者接受

  • 导入
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as mdates
import datetime
from matplotlib.font_manager import FontProperties

一、Figure和Axes上的文本

1.基本文本API

pyplot APIOO APIdescription
texttext在子图axes的任意位置添加文本
annotateannotate在子图axes的任意位置添加注解,包含指向性的箭头
xlabelset_xlabel在的 x 轴上添加标签
ylabelset_ylabel在的 y 轴上添加标签
titileset_title添加标题
figtexttext在画布figure的任意位置添加文本
suptitlesuptitle为画布figure添加标题
  • 例子
fig = plt.figure()
ax = fig.add_subplot()


# 分别为figure和ax设置标题,注意两者的位置是不同的
fig.suptitle('Figure suptitle', fontsize=14, fontweight='bold')  # fontweight='bold' 加粗
ax.set_title('Axes title')

# 设置x和y轴标签
ax.axis([0, 10, 0, 10]) # 设置x和y轴显示范围均为0到10
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')


# 在子图上添加文本
ax.text(3.5, 8, 'This is a text in box', style='italic',
        bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
ax.text(2, 6, r'An equation: $x^2+y^2=z^2$', fontsize=15)


# 在画布上添加文本,一般在子图上添加文本是更常见的操作,这种方法很少用
fig.text(0.4,0.8,'This is text for figure')

ax.plot([6], [1], 's') # 依次为:横坐标、纵坐标、形状
# 添加注解
ax.annotate('annotate', xy=(6, 1), xytext=(1, 3),arrowprops=dict(facecolor='green', shrink=0.05));

在这里插入图片描述


2.text - 子图上的文本

text的调用方式为Axes.text(x, y, s, fontdict=None, **kwargs)
其中x,y为文本出现的位置,默认状态下即为当前坐标系下的坐标值,s为文本的内容,fontdict是可选参数,用于覆盖默认的文本属性,**kwargs为关键字参数,也可以用于传入文本样式参数

  • 例子
fig = plt.figure(figsize=(10,3))
axes = fig.subplots(1,2)

# 使用fontdict参数修改文本样式
font = {'bbox':{'facecolor': 'red', 'alpha': 0.5, 'pad': 10}, 'style':'italic'}
axes[0].text(0.3, 0.8, 'modify by fontdict', fontdict=font);

# 使用关键字参数修改文本样式
axes[1].text(0.3, 0.8, 'modify by **kwargs', style='italic',
        bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10});

在这里插入图片描述


3.xlabel和ylabel - 子图的x,y轴标签

set_xlabel通过andset_ylabel 方法指定 x 轴和 y 轴的标签很简单
-例子

x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig = plt.figure(figsize=(20,3))
ax = fig.subplots(1,3)

# 基本
fig.subplots_adjust(bottom=0.15, left=0.2)
ax[0].plot(x1, y1)
ax[0].set_xlabel('Time [s]')
ax[0].set_ylabel('Damped oscillation [V]')


# FontProperties
font = FontProperties()
font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('italic')
font.set_weight('normal')

ax[1].plot(x1, y1*1000)
ax[1].set_xlabel('Time [s]', fontsize='large', fontweight='bold') # 字体变大,加粗
ax[1].set_ylabel('Damped oscillation [V]', fontproperties=font) # 字体为“Times New Roman”

# 使用本机 TeX 渲染并拥有多行
ax[2].plot(x1, y1)
ax[2].set_xlabel('time [s] \n This was a long experiment')
ax[2].set_ylabel(r'$\cos(2*\pi*x)*e^x$')

plt.show()

在这里插入图片描述


4.title和suptitle - 子图和画布的标题

title的调用方式为Axes.set_title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
其中label为子图标签的内容,fontdict,loc,**kwargs和之前小节相同不重复介绍
pad是指标题偏离图表顶部的距离,默认为6
ytitle所在子图垂向的位置。默认值为1,即title位于子图的顶部。

suptitle的调用方式为figure.suptitle(t, **kwargs)
其中t为画布的标题内容

  • 例子
fig, axs = plt.subplots(3, 1, figsize=(5, 6), tight_layout=True)
locs = ['center', 'left', 'right']
for ax, loc in zip(axs, locs):
    ax.plot(x1, y1)
    ax.set_title('Title with loc at '+loc, loc=loc)
plt.show()

在这里插入图片描述


5.字体的属性设置

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

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plt.plot(x, label='小示例图标签')

# 直接用字体的名字
plt.xlabel('x 轴名称参数', fontproperties='Microsoft YaHei', fontsize=16)         # 设置x轴名称,采用微软雅黑字体
plt.ylabel('y 轴名称参数', fontproperties='SimSun', fontsize=14)                 # 设置Y轴名称,采用宋体
plt.title('坐标系的标题',  fontproperties='FangSong', fontsize=20)              # 设置坐标系标题的字体,采用仿宋
plt.legend(loc='lower right', prop={"family": 'FZYaoti'}, fontsize=10) ;  # 小示例图的字体设置,采用方正姚体

在这里插入图片描述


二、Tick上的文本

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

  • 简单例子
# 使用axis的set_ticks方法手动设置标签位置的例子
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
axs[0].plot(x1, y1)
axs[1].plot(x1, y1)
axs[1].xaxis.set_ticks(np.arange(0., 8.1, 2.))
plt.show()

在这里插入图片描述


# 使用axis的set_ticklabels方法手动设置标签格式的例子
fig, axs = plt.subplots(3, 1, figsize=(8, 4), tight_layout=True)
axs[0].plot(x1, y1)

# 一
axs[1].plot(x1, y1)
ticks = np.arange(0., 8.1, 2.)
tickla = [f'{tick:1.2f}' for tick in ticks]
axs[1].xaxis.set_ticks(ticks)
axs[1].xaxis.set_ticklabels(tickla);

# 二
axs[2].plot(x1, y1)
axs[2].set_xticks([0,1,2,3,4,5,6])                                               # 设置x轴的刻度位置
axs[2].set_xticklabels(['zero','one', 'two', 'three', 'four', 'five','six'],    #设置刻度对应的标签
                   rotation=30, fontsize='small')                              #rotation选项设定x刻度标签倾斜30度。
axs[2].xaxis.set_ticks_position('bottom'                                     )#set_ticks_position()方法是用来设置刻度所在的位置,常用的参数有bottom、top、both、none
plt.show()

在这里插入图片描述

  • Tick Locators and Formatters

除了上述的简单模式,还可以使用Tick Locators and Formatters完成对于刻度位置和刻度标签的设置。
其中,Axis 具有使用绘制的数据确定主要和次要位置的方法Axis.set_major_locator。Axis.set_minor_locator还有一些格式化刻度标签Axis.set_major_formatter的Axis.set_minor_formatter方法。

A. Tick Locators

# 接收各种locator的例子
fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
for n, ax in enumerate(axs.flat):
    ax.plot(x1*10., y1)

locator = matplotlib.ticker.AutoLocator()
axs[0, 0].xaxis.set_major_locator(locator)

locator = matplotlib.ticker.MaxNLocator(nbins=10)
axs[0, 1].xaxis.set_major_locator(locator)


locator = matplotlib.ticker.MultipleLocator(5)
axs[1, 0].xaxis.set_major_locator(locator)


locator = matplotlib.ticker.FixedLocator([0,7,14,21,28])
axs[1, 1].xaxis.set_major_locator(locator);

在这里插入图片描述


B. Tick Formatters

# Tick Formatters
# 接收字符串格式的例子
fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
for n, ax in enumerate(axs.flat):
    ax.plot(x1*10., y1)

formatter = matplotlib.ticker.FormatStrFormatter('%1.1f')
axs[0, 1].xaxis.set_major_formatter(formatter)

formatter = matplotlib.ticker.FormatStrFormatter('-%1.1f')
axs[1, 0].xaxis.set_major_formatter(formatter)

formatter = matplotlib.ticker.FormatStrFormatter('%1.5f')
axs[1, 1].xaxis.set_major_formatter(formatter);

在这里插入图片描述

# 接收函数的例子
def formatoddticks(x, pos):
    """Format odd tick positions."""
    if x % 2:
        return f'{x:1.2f}'
    else:
        return ''

fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
ax.plot(x1, y1)
ax.xaxis.set_major_formatter(formatoddticks);

在这里插入图片描述

参考

Datawhale🐳数据可视化小组开源项目:《Fantastic-Matplotlib》

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值