基本上,我正在做可伸缩性分析,所以我正在处理像 2,4,8,16,32... 等数字,图形看起来合理的唯一方法是使用对数刻度。

但不是通常的 10^1、10^2 等标签,我希望在轴上指示这些数据点 (2,4,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()

关于python - PyLab : Plotting axes to log scale, 但在轴上标记特定点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5605503/

10-11 07:32