PyLab:绘制轴以记录比例,但标记轴上的特定点

时间:2011-04-09 14:04:01

标签: python graph matplotlib

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

但不是通常的10 ^ 1,10 ^ 2等标签,我想在轴上显示这些数据点(2,4,8 ...)

有什么想法吗?

1 个答案:

答案 0 :(得分: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()

enter image description here

如果你想以更灵活的方式做到这一点,那么也许你可以使用这样的东西:

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()

enter image description here

或类似的东西:

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()

enter image description here