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

Bol*_*ter 4 python graph matplotlib

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

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

有任何想法吗?

Joe*_*ton 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

或类似的东西:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述