繁体   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