如何调整Matplotlib对数图Y轴主刻度间距及副刻度设置
Hey there! Let's get that y-axis tick setup working for your log plot.
The issue with your original approach is that Matplotlib's LogLocator doesn't play nicely with bases less than 1—it's designed primarily for bases greater than 1, which is why your base=0.01 setting didn't produce the expected results. But don't worry, we can achieve exactly what you want using base=10 and tweaking the subs parameter to match your desired intervals.
Here's the revised code with explanations:
import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as mtick x = np.array([1, 5, 10, 32]) y = np.array([0.34, 0.27, 0.25, 0.21]) yerr = np.array([0.02, 0.019, 0.019, 0.016]) fig, ax = plt.subplots() res = ax.errorbar(x, y, yerr=yerr, fmt='.', ls='') ax.set_xscale('log') ax.set_yscale('log') # Configure major y-ticks: 0.1 interval (0.1, 0.2, 0.3, etc.) # We use base=10 and specify subs to target multiples of 0.1 ax.yaxis.set_major_locator(mtick.LogLocator(base=10, subs=[1, 2, 3, 4])) # Format major tick labels as decimals instead of scientific notation ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.1f')) # Configure minor y-ticks: 0.01 interval, no labels # subs=np.arange(1,10)/10 creates ticks at every 0.01 increment within each 0.1 range ax.yaxis.set_minor_locator(mtick.LogLocator(base=10, subs=np.arange(1, 10)/10, numticks=10)) # Hide minor tick labels ax.yaxis.set_minor_formatter(mtick.NullFormatter()) plt.show()
Key Details:
- Major Ticks: Using
base=10withsubs=[1,2,3,4]tells Matplotlib to place major ticks at1*10^-1=0.1,2*10^-1=0.2,3*10^-1=0.3, etc.—exactly your desired 0.1 interval. The formatter ensures labels show up as clean decimals instead of scientific notation. - Minor Ticks:
subs=np.arange(1,10)/10generates ticks at every 0.01 step (e.g., 0.11, 0.12, ..., 0.19, 0.21, ...). We useNullFormatter()to hide the labels so only the tick marks appear.
This approach works reliably because it leverages Matplotlib's intended behavior for LogLocator while still achieving your custom tick spacing requirements.
内容的提问来源于stack exchange,提问作者Thomas Mann
相关产品推荐
相关产品推荐

