【发布时间】: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