Matplotlib 标签正字体问题:保持原始刻度字体

Matplotlib 标签正字体问题:保持原始刻度字体

在数据可视化中,轴标签是控制数据解释的重要元素。Matplotlib是Python中常用的数据可视化库,其中字体设置是一个常见的问题。本文将探讨如何保持标签原始字体,避免旋转标签出现字体倾斜等问题。

阅读更多:Matplotlib 教程

问题描述

我们先从一幅图开始:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)
y = np.random.rand(10)

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticks(x)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
plt.show()

这是一个简单的直线图,横坐标刻度使用英文字母表示。

显然,字母标签已经倾斜了。当刻度标签过长时,自动旋转每个标签可以帮助更好地展示标签,这个设置是默认的。但有时候,我们想要保持图形的纵向方向,避免字体倾斜,这时候我们就需要更改这个设置。

方案1: 清除旋转

我们可以通过 xtick.label.set_rotation() 来设置标签旋转的角度,将角度设置为0度,就可以避免字体倾斜:

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticks(x)
xl = ax.set_xticklabels(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
for label in xl:
    label.set_rotation(0)

plt.show()

这里将旋转角度设置为0度。

这种方法简单易行,但是如果每次都要手动设置 set_rotation() 的话,就会很繁琐不方便。所以,接下来我们将介绍更加通用的解决方法。

方案2: 使用RcParams设置

Matplotlib的核心组件 rcParams 控制了绘图的许多属性,它们可以在全局范围内设置,以影响所有图或子图。我们可以从默认设置中更改标签旋转以避免字体倾斜的问题。

import matplotlib as mpl

mpl.rcParams['xtick.labelrotation'] = 0

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticks(x)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
plt.show()

这里设置 xtick.labelrotation 的值为0度即可。后续的图形展示与方案1的结果一致。

我们可以将设置写入Matplotlib的配置文件中,从而永久更改默认值。matplotlibrc(也就是Matplotlib的配置文件)可以通过 mpl.matplotlib_fname() 找到,然后编辑该文件即可。

文件开头的默认设置如下:

## CONFIGURATION BEGINS HERE

# The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg cairo GDK PS PDF SVG
# Template.
# You can also deploy your own backend outside of matplotlib by
# referring to thematplotlib.backends module with, for example, module://my_backend.
# The choices need to be defined as class variables on the backend module.
# If comments in your backend string, place a hash (`#`) before it
# as this may cause errors on certain configurations (like macOS).
#backend      : TkAgg

# matplotlib can also use LaTeX to render text.  LaTeX is installed
# via `sudo apt-get install texlive-latex-extra` on Ubuntu.
# You will also need to have ghostscript installed for printing to
# Postscript/PDF and dvipng installed for previewing images on the screen.
#
# See https://matplotlib.org/3.3.4/tutorials/text/usetex.html for more info.
#usepgf          : False
#pgf.rcfonts     : False
#pgf.texsystem   : xelatex
#pgf.preamble    : 

# Path to save figures (may be relative or absolute).
# Examples:
#   'figure_directory' will save figures to a directory called
#   'figure_directory'.
#   '/path/to/figure/directory' will save figures to a directory called
#   'directory' located at '/path/to/figure'.
#   The directory name will be assumed to be relative to the current working
#   directory if it starts with '.'; it will be assumed to be relative to
#   the home directory if it starts with '~' (or to the root directory,
#   if it starts with '/').
#
# See https://matplotlib.org/3.3.4/tutorials/introductory/customizing.html#the-configuration-file-location
# for more details on the config file locations.
#savefig.directory : ~


#### CONFIGURATION END

# Warning: Most of the below are NOT intended to be changed.  They should
# be considered read-only files that are managed by Matplotlib.  Changes
# to them may cause Matplotlib to malfunction.

我们可以在该文件中搜索 xtick.labelrotation,找到其所在行,并将设置的值改为我们需要的值。

方案3: 使用style

Matplotlib还提供了多种预定的风格样式,可以通过 plt.style.use() 改变图形的样式。其中,ggplot 风格为常用的一种。使用该样式,不仅可以避免标签旋转导致的字体倾斜,而且还有更良好的视觉效果。

plt.style.use('ggplot')

fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticks(x)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])
plt.show()

这种风格样式在多数情况下都会让图形更美观、更易读。

总结

本文介绍了三种方法来解决Matplotlib中标签旋转导致字体倾斜的问题:

  1. 清除旋转:手动设置 set_rotation()
  2. 使用RcParams设置:设置默认值,同时可以将设置写入到配置文件中,以更改默认值。
  3. 使用style:Matplotlib提供的多种预定的风格样式,例如 ggplot 风格。

根据不同的需求,可以选择合适的方法来解决标签旋转的问题,以达到较好的数据解释和美观的图形展示效果。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程