首页 > 解决方案 > 如何在 ScalarFormatter 之后更改对数图的 xticks 和 yticks?

问题描述

我有这个代码:

 # Modules I import 

    import matplotlib
    if os.environ.get('DISPLAY','') == '':
        print('no display found. Using non-interactive Agg backend')
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from matplotlib.ticker import ScalarFormatter
    from pylab import *

# My Variables to plot

    ideal_walltime_list = [135.82, 67.91, 33.955, 16.9775, 8.48875]
    cores_plotting = [16, 32, 64, 128, 256]
    time_plotting = [135.82, 78.69, 50.62, 46.666, 42.473]

# My plotting part
    plt.figure()
    plt.scatter(cores_plotting, time_plotting, c='r', label='System wall time')
    plt.plot(cores_plotting, ideal_walltime_list, c='k', label='Ideal Wall time')

    plt.title('109bEdec_test')
    plt.ylabel('Wall time (s)')

    plt.xlabel('Cores')
    plt.legend(loc='upper right')
    plt.yscale('log')
    plt.xscale('log')

    ax = gca().xaxis
    ax.set_major_formatter(ScalarFormatter())
    ax.set_minor_formatter(ScalarFormatter())

    ay = gca().yaxis
    ay.set_major_formatter(ScalarFormatter())
    ay.set_minor_formatter(ScalarFormatter())
    plt.savefig('109bEdec_test' + '.png',dpi=1800)


    plt.show()

当我运行此代码时,我的情节如下所示:

在此处输入图像描述

但是,我需要我的 x 轴和 y 轴来显示对应于我的 cores_plotting 变量的刻度,而不是所有格式错误的数字。我试过使用:

plt.xticks(cores_plotting)
plt.yticks(cores_plotting)

但没有成功。

我也试过:

plt.xticks(cores_plotting, ('16', '32', '64', '128', '256'))
plt.yticks(cores_plotting, ['16', '32', '64', '128', '256'])

但也没有成功。现在我只需要将 cores_plotting 项目作为我的 X 和 Y 刻度。

我的 python 版本是 3.6.5,我的 Matplotlib 版本是 3.0.2。

谢谢!

标签: pythonpython-3.xmatplotlib

解决方案


您可以先放置将充当主要刻度的自定义刻度,然后隐藏次要刻度。您需要创建一个轴句柄ax来访问次要刻度。请检查您用于 y-ticklabels 的字符串。

fig, ax = plt.subplots()
plt.scatter(cores_plotting, time_plotting, c='r', label='System wall time')
plt.plot(cores_plotting, ideal_walltime_list, c='k', label='Ideal Wall time')

# Rest of your code here

ax.set_yticks(cores_plotting) 
ax.set_yticklabels(['16', '32', '64', '128', '256'])

ax.set_xticks(cores_plotting) 
ax.set_xticklabels(['16', '32', '64', '128', '256'])

for xticks in ax.xaxis.get_minor_ticks():
    xticks.label1.set_visible(False)
    xticks.set_visible(False)

for yticks in ax.yaxis.get_minor_ticks():
    yticks.label1.set_visible(False)
    yticks.set_visible(False)

Matplotlib 版本问题

matplotlib似乎以下命令在3+ 版本中不起作用并抛出

TypeError: 'list' object is not callable` 错误。

在这种情况下,使用上述方法分配刻度和刻度标签。

plt.xticks(cores_plotting, ['16', '32', '64', '128', '256']);
plt.yticks(cores_plotting, ['16', '32', '64', '128', '256'])

在此处输入图像描述


推荐阅读