PyLab:绘制对数坐标轴,但标记特定点

4 投票
1 回答
6220 浏览
提问于 2025-04-16 15:23

基本上,我在做可扩展性分析,所以我在处理一些数字,比如2、4、8、16、32等等。为了让图表看起来更合理,我需要使用对数刻度。

不过,我不想用通常的10的幂次(比如10^1、10^2等)来标记,而是想在坐标轴上直接显示这些数据点(2、4、8……)。

有没有什么好主意?

1 个回答

8

其实有很多种方法可以做到这一点,具体取决于你想要多灵活或多花哨。

最简单的方法就是这样做:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.exp2(np.arange(10))

plt.semilogy(x)
plt.yticks(x, x)

# Turn y-axis minor ticks off 
plt.gca().yaxis.set_minor_locator(mpl.ticker.NullLocator())

plt.show()

在这里输入图片描述

如果你想要更灵活一点的做法,可能可以试试这样的:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.exp2(np.arange(10))

fig = plt.figure()
ax = fig.add_subplot(111) 
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)

# This will place 1 minor tick halfway (in linear space) between major ticks
# (in general, use np.linspace(1, 2.0001, numticks-2))
ax.yaxis.get_minor_locator().subs([1.5])

ax.yaxis.get_major_formatter().base(2)

plt.show()

在这里输入图片描述

或者可以用这样的方式:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

x = np.exp2(np.arange(10))

fig = plt.figure()
ax = fig.add_subplot(111) 
ax.semilogy(x)
ax.yaxis.get_major_locator().base(2)
ax.yaxis.get_minor_locator().base(2)

ax.yaxis.get_minor_locator().subs([1.5])

# This is the only difference from the last snippet, uses "regular" numbers.
ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

plt.show()

在这里输入图片描述

撰写回答