Python使用Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法

  

当Python中的Matplotlib模块用于绘制图形时,往往需要对图形进行标注,比如绘图的横坐标或纵坐标需要加上中文标题或特殊符号。但是,Matplotlib默认情况下并不支持这些特殊字符的显示,需要进行一些设置和转换才能实现。下面是使用Python中的Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法的完整攻略。

  1. 配置字体

Matplotlib中的默认字体是英文,为了支持中文或特殊符号的显示,需要配置Matplotlib中的字体。可以采用以下三种方法:

1) 使用rcParams:

使用rcParams可以在程序的任意位置进行字体设置,具体设置方法如下:

import matplotlib as mpl
font = {'family' : 'MicroSoft YaHei','weight' : 'bold','size'   : '16'}
mpl.rc('font', **font)

注释:

  • 'MicroSoft YaHei':字体名称,可以按照需要替换为其他支持中文的字体名。
  • 'bold':字体粗细,可以按照需要替换为其他值。
  • '16':字体大小,可以按照需要替换为其他值。

2) 使用Matplotlib.rcParams:

Matplotlib提供了RCPParams类用来管理自定义设置,通过如下方法可以进行字体设置:

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=14) 

plt.title(u'中国联系人')

注释:

  • 通过导入‘from matplotlib.font_manager import FontProperties’ 实现字体设置。
  • 通过指定fname参数来指定字体文件的路径并设置其大小。

3) 修改matplotlibrc文件:

Matplotlibrc是Matplotlib的配置文件,可以实现所有的自定义设置。可以通过修改该文件实现对字体的配置。步骤如下:

  • 寻找主题配置文件路径:
import matplotlib as mpl
mpl.matplotlib_fname()
  • 配置Matplotlibrc:

在主题配置文件路径中找到‘matplotlibrc’文件,打开该文件并进行如下配置:

font.family         : MicroSoft YaHei 
  1. 设置字体和编码

设置完字体之后,还需要设置编码。对于Windows系统来说,最好选择utf-8编码,同时需要用到特定的字体,常用命令如下:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from pylab import *
mpl.rcParams['font.sans-serif'] = ['YY']
mpl.rcParams['axes.unicode_minus'] = False 
# 设置字体
mpl.rcParams['font.sans-serif']=['SimHei'] 
# 解决中文乱码问题
mpl.rcParams['axes.unicode_minus']=False
# 解决负号无法显示的问题
x = ['一','二','三','四','五']
y = [20, 30, 40, 50, 60]

plt.bar(x, y)
plt.xlabel(u'x轴名称')
plt.ylabel(u'y轴名称')
plt.title(u'中文标题')
plt.show()

注释:

  • 'YY':字体名称,可以按照需要替换为其他支持中文的字体名。
  • 'SimHei':字体名称,可以按照需要替换为其他支持中文的字体名。
  • 'axes.unicode_minus':Matplotlib默认情况下,负号显示为方块,需要设置为False来解决这个问题。
  • ‘u’:前缀用来指定编码格式为utf-8。

  • 使用Latex

除了上述方法外,还可以使用Latex引擎来支持中文的显示,这需要进行如下设置:

# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['text.usetex'] = True
plt.rcParams['axes.unicode_minus'] = False
x = ['一', '二', '三', '四', '五']
y = [20, 30, 40, 50, 60]
plt.bar(x, y)
plt.title(r'\textbf{标题}', fontsize=16)
plt.xlabel(r'\textit{横坐标}', fontsize=14)
plt.ylabel(r'\textsl{纵坐标}', fontsize=14)
plt.show()

注释:

  • “text.usetex”: 设置为True可以让Matplotlib使用Tex引擎渲染文字。
  • “\textbf{..}”:用于设置字符的粗细。
  • “\textit{..}”:用于设置字符的斜体。
  • “\textsl{..}”:用于设置字符的倾斜。

示例1:绘制直方图

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False 

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# 数据的直方图
n, bins, patches = plt.hist(x, 50, density=True, facecolor='g', alpha=0.75)

plt.xlabel('时间')
plt.ylabel('频率')
plt.title('时间频率分布')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

注释:

  • r'$\mu=100,\ \sigma=15$':LaTex引擎中的公式,支持变量。

示例2:雷达图

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt

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

# 绘制雷达图所需参数
name_list = ['a', 'b', 'c', 'd', 'e']
data = [90, 30, 40, 50, 60]
data = np.concatenate((data, [data[0]]))  # 闭合

angles = np.linspace(0, 2 * np.pi, len(name_list), endpoint=False)
angles = np.concatenate((angles, [angles[0]]))  # 闭合

# 绘图
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
ax.plot(angles, data, 'bo-', linewidth=2)
ax.fill(angles, data, facecolor='g', alpha=0.3)
ax.set_thetagrids(angles * 180 / np.pi, name_list)
ax.set_title(u"雷达图", fontproperties='SimHei', fontsize=20)
ax.set_rlim(0, 100)

plt.show()

注释:

  • ‘polar=True’:设置成极坐标系。
  • facescolor:面的颜色。
  • alpha:面的透明度。

以上是使用Python中Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法的完整攻略。

相关文章