022540341 suxin 课程作业
第 6 章 / 共 7 章

坐标轴的定制

坐标轴决定了读者怎么读数。刻度太密会糊成一片,太稀会读不准;双变量单位不同时还得请出双 y 轴。

本章目录

  1. 6.1 刻度位置与标签:set_xticks / set_xticklabels
  2. 6.2 刻度密度与格式:MultipleLocator / FuncFormatter
  3. 6.3 双 y 轴:twinx 处理量纲不同的两个变量
  4. 6.4 轴脊与坐标轴交叉点:spines
6.1

刻度位置与标签:set_xticks / set_xticklabels

默认刻度往往太密或标签太长,手动指定刻度位置并旋转标签是最常见的处理。

刻度位置与标签:set_xticks / set_xticklabels

12 个月全部显示会挤,这里保留全部刻度但旋转 45°、右对齐,y 轴只保留 6 个刻度。

python
import matplotlib.pyplot as plt

months = ['%d月' % i for i in range(1, 13)]
sales = [88, 92, 105, 98, 120, 132, 128, 140, 135, 150, 158, 175]

plt.figure(figsize=(7.4, 4.2))
plt.plot(months, sales, marker='o', color='#2f6f5e')

plt.xticks(rotation=45, ha='right')
plt.yticks([80, 100, 120, 140, 160, 180])
plt.title('全年销售额走势')
plt.ylabel('销售额(万元)')
plt.tight_layout()
plt.show()
6.2

刻度密度与格式:MultipleLocator / FuncFormatter

刻度间隔固定用 MultipleLocator,把数字变成百分比、千分位这类格式用 FuncFormatter。

刻度密度与格式:MultipleLocator / FuncFormatter

x 轴每 1 个单位一个主刻度,y 轴以百分比显示(0%—80%)。

python
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FuncFormatter

quarters = [0, 1, 2, 3, 4]
rate = [0.15, 0.32, 0.48, 0.61, 0.77]

fig, ax = plt.subplots(figsize=(7.4, 4.2))
ax.plot(quarters, rate, marker='o', color='#2f6f5e')

ax.set_xlim(0, 4)
ax.xaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_formatter(FuncFormatter(lambda v, pos: f'{v:.0%}'))

ax.set_xlabel('季度')
ax.set_ylabel('累计转化率')
ax.set_title('刻度密度与百分比格式')
plt.tight_layout()
plt.show()
6.3

双 y 轴:twinx 处理量纲不同的两个变量

营收是「万元」、利润率是「百分比」,共用一根 y 轴会让小的那条线被压扁,这时用 twinx 再开一根右侧 y 轴。

双 y 轴:twinx 处理量纲不同的两个变量

左轴柱形图是营收,右轴折线是利润率,两套刻度各自独立。

python
import matplotlib.pyplot as plt

quarters = ['一季度', '二季度', '三季度', '四季度']
revenue = [210, 240, 265, 300]
profit = [18, 21, 19, 24]

fig, ax1 = plt.subplots(figsize=(7.4, 4.2))
ax1.bar(quarters, revenue, width=0.5, color='#8fb5a8', label='营收')
ax1.set_ylabel('营收(万元)')
ax1.set_ylim(0, 360)

ax2 = ax1.twinx()
ax2.plot(quarters, profit, marker='o', color='crimson', label='利润率')
ax2.set_ylabel('利润率(%)')
ax2.set_ylim(0, 30)

lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left', frameon=False)

ax1.set_title('营收与利润率(双 y 轴)')
plt.tight_layout()
plt.show()
6.4

轴脊与坐标轴交叉点:spines

spines 是绘图区的四条边框,删掉上面和右边会显得更现代;把 left 和 bottom 移到数据 0 点,就变成数学课本里的坐标轴。

轴脊与坐标轴交叉点:spines

隐藏上、右轴脊,并把左、下轴脊移动到过原点的位置。

python
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-6, 6, 200)

fig, ax = plt.subplots(figsize=(7.4, 4.4))
ax.plot(x, 0.35 * x ** 2 - 3, color='#2f6f5e')

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_position(('data', 0))
ax.spines['bottom'].set_position(('data', 0))

ax.set_title('坐标轴移到原点(spines)', pad=16)
plt.tight_layout()
plt.show()