简体   繁体   中英

Add custom logarithmic tick location to matplotlib

I have a line plot, where the x-axis is logarithmic. I would like to mark a specific value on this axis (40000). This means I would like to insert a custom major tick at this location. I've tried to explicitly set the xticks using set_xticks() generated from numpy's logspace which kinda works, but does not automatically add a label for the extra tick. How can I do that? Also, can I customize the grid line for this extra tick?

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

And this is the output I get with the desired output marked. 在此处输入图像描述

Edit Thanks for the answers, they are great solutions using FuncFormatter . I did however stumble across a solution using axvline to add a vertical line at 200x200. This is my new solution, using minor ticks for the extra tick.

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

Which produces the final result: 在此处输入图像描述

You can give a try to use ScalarFormatter() after setting the xticks.

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

A similar question has been asked previously. You can check that as well set ticks with logarithmic scale

There is a post explaining in-depth for the log scalehttps://atmamani.github.io/cheatsheets/matplotlib/matplotlib_2/

I hope it helps:-)

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

Format set corresponding grid line:

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

例子

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM