簡體   English   中英

將自定義對數刻度位置添加到 matplotlib

[英]Add custom logarithmic tick location to matplotlib

我有一條線 plot,其中 x 軸是對數的。 我想在這個軸上標記一個特定的值(40000)。 這意味着我想在這個位置插入一個自定義的主要刻度。 我嘗試使用從 numpy 的日志空間生成的set_xticks()顯式設置logspace ,這有點工作,但不會自動為額外的刻度添加 label。 我怎樣才能做到這一點? 另外,我可以為這個額外的刻度自定義網格線嗎?

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

這是我得到的 output,上面標有所需的 output。 在此處輸入圖像描述

編輯感謝您的回答,它們是使用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()

產生最終結果: 在此處輸入圖像描述

您可以在設置 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())

之前有人問過類似的問題。 您還可以檢查是否使用對數刻度設置刻度

有一篇文章深入解釋了對數刻度https://atmamani.github.io/cheatsheets/matplotlib/matplotlib_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')

例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM