【问题标题】:Add custom logarithmic tick location to matplotlib将自定义对数刻度位置添加到 matplotlib
【发布时间】:2020-07-09 10:40:35
【问题描述】:

我有一个线图,其中 x 轴是对数的。我想在这个轴上标记一个特定的值(40000)。这意味着我想在这个位置插入一个自定义的主要刻度。我尝试使用从 numpy 的 logspace 生成的 set_xticks() 显式设置 xticks,这有点工作,但不会自动为额外的刻度添加标签。我怎样才能做到这一点?另外,我可以为这个额外的刻度自定义网格线吗?

fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.power(sizes, 2), hsv_mat_times, label="HSV Material Shader")
ax.plot(np.power(sizes, 2), brick_mat_times, label="Brick Material Shader")
ax.set_title("Python Shader Rendering Performance")
ax.set_xlabel("Number of Pixels")
ax.set_ylabel("CPU Rendering Time (ms)")
formatter = FuncFormatter(lambda x, pos: "{:.3}".format(x / 1000000))
xticks = np.logspace(2,6,num=5)
xticks = np.insert(xticks,4,200*200)
ax.set_xscale("log")
ax.set_xticks(xticks)
ax.legend()
plt.show()

这是我得到的输出,标记了所需的输出。

编辑 感谢您的回答,它们是使用 FuncFormatter 的绝佳解决方案。然而,我确实偶然发现了一个使用axvline 在 200x200 处添加垂直线的解决方案。这是我的新解决方案,使用次要刻度作为额外刻度。

def log_format(x, pos):
    return "$200\\times 200$"

fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.power(sizes, 2), hsv_mat_times, label="HSV Material Shader")
ax.plot(np.power(sizes, 2), brick_mat_times, label="Brick Material Shader")
ax.plot(np.power(sizes, 2), hsv_mat_times2, label="PLACEHOLDER FOR 3rd shader")
ax.set_title("Python Shader Rendering Performance", fontsize=18)
ax.set_xlabel("Number of Pixels")
ax.set_ylabel("CPU Rendering Time (ms)")
ax.set_xscale("log")
ax.set_xticks([200*200], minor=True)
ax.xaxis.grid(False, which="minor")
ax.axvline(200*200, color='white', linestyle="--")
ymin,ymax = ax.get_ylim()
ax.text(200*200 - 200*50, (ymax-ymin)/2, "Default render size", rotation=90, va="center", style="italic")
ax.xaxis.set_minor_formatter(FuncFormatter(log_format))
ax.legend()
plt.show()

产生最终结果:

【问题讨论】:

    标签: python numpy matplotlib logarithm


    【解决方案1】:

    你可以在设置xticks后尝试使用ScalarFormatter()

    xticks = np.logspace(2,6,num=5)
    xticks = np.insert(xticks,4,200*200)
    ax.set_xscale("log")
    ax.set_xticks(xticks)
    
    # add this line
    ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
    

    之前有人问过类似的问题。你也可以检查一下 set ticks with logarithmic scale

    有一篇文章深入解释了对数刻度 https://atmamani.github.io/cheatsheets/matplotlib/matplotlib_2/

    希望对你有帮助:-)

    【讨论】:

    • 嗨!是的,我看到了,它实际上显示了我的刻度,但格式错误。我仍然希望它使用对数表示法。我想我可以使用FuncFormatter 来解决这个问题……
    【解决方案2】:
    from matplotlib.ticker import FuncFormatter, LogFormatterMathtext
    ax.xaxis.set_major_formatter(FuncFormatter(lambda x,_: '$\\mathdefault{0.4*10^{5}}$' if x == 40000 else LogFormatterMathtext()(x)))
    

    格式设置对应的网格线:

    ax.xaxis.get_gridlines()[4].set_c('r')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 2013-01-20
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      相关资源
      最近更新 更多