首页 > 解决方案 > 如何在 Matplotlib 中定义自定义轴?

问题描述

假设我有以下代码:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(520)
y = np.random.rand(520)
plt.plot(x, y)

这会产生以下图表:

在此处输入图像描述

如何定义自定义轴,使我的 X 轴如下所示:

在此处输入图像描述

标签: pythonmatplotlib

解决方案


您可以使用:

  • plt.xscale('log')将比例更改为对数比例
  • set_major_formatter(ScalarFormatter())将格式设置回正常(替换LogFormatter
  • set_minor_locator(NullLocator())删除次要刻度(也由对数刻度设置)
  • set_major_locator(FixedLocator([...]plt.xticks([...])在 x 轴上设置所需的刻度
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, NullLocator, FixedLocator
import numpy as np

x = np.arange(520)
y = np.random.uniform(-1, 1, 520).cumsum()
plt.plot(x, y)
plt.xscale('log')
# plt.xticks([...])
plt.gca().xaxis.set_major_locator(FixedLocator([2**i for i in range(0, 7)] + [130, 260, 510]))
plt.gca().xaxis.set_major_formatter(ScalarFormatter())
plt.gca().xaxis.set_minor_locator(NullLocator())
plt.show()

示例图


推荐阅读