首页 > 解决方案 > Matplotlib 对数图 - 仅在 y 轴上显示 10 的幂

问题描述

假设我有以下代码:

import matplotlib as mpl
from matplotlib import pyplot as plt
x =[10, 14, 19, 26, 36, 50, 70, 98, 137, 191, 267, 373, 522, 730, 1021, 1429, 2000, 2800, 3919, 5486, 7680] 
y = [ 0.0085,  0.006900000000000001,  0.007600000000000001,  0.007600000000000001,  0.01,  0.008700000000000003,  0.0094,  0.008800000000000002,  0.0092,  0.009,  0.009999999999999998,  0.010099999999999998,  0.010899999999999998,  0.010899999999999998, 0.011,  0.0115,   0.0115,  0.0118,  0.013000000000000001,  0.0129, 0.0131]
fig, ax1 = plt.subplots() 
ax1.plot(x,y,linewidth=1) 
ax1.set_xscale('log') 
ax1.set_yscale('log') 
plt.show()

结果如下:

在此处输入图像描述

我想要做的是删除 y 轴上不是10 的幂的刻度。在这个特定的例子中,删除 9x10^-3、8x10^-3 等,只保留 10^-2。

我尝试了其他一些建议,例如这个,但没有一个有效..有什么想法吗?

标签: pythonpython-3.xmatplotlibplot

解决方案


您可以在最小和最大 y 值之间找到 10 的所有幂,然后使用 直接设置刻度ax1.set_yticks( y_ticks)

import matplotlib as mpl
from matplotlib import pyplot as plt
import math 

x =[10, 14, 19, 26, 36, 50, 70, 98, 137, 191, 267, 373, 522, 730, 1021, 1429, 2000, 2800, 3919, 5486, 7680] 
y = [ 0.0085,  0.006900000000000001,  0.007600000000000001,  0.007600000000000001,  0.01,  0.008700000000000003,  0.0094,  0.008800000000000002,  0.0092,  0.009,  0.009999999999999998,  0.010099999999999998,  0.010899999999999998,  0.010899999999999998, 0.011,  0.0115,   0.0115,  0.0118,  0.013000000000000001,  0.0129, 0.0131]
fig, ax1 = plt.subplots() 
ax1.plot(x,y,linewidth=1) 
ax1.set_xscale('log') 
ax1.set_yscale('log')

ymin_pow = math.floor(math.log10(min(y)))
ymax_pow = math.ceil(math.log10(max(y)))

y_ticks = [10**i for i in range(ymin_pow, ymax_pow + 1)]

# optional: bound the limits 
if y_ticks[0] < min(y):
    y_ticks = y_ticks[1:]
if y_ticks[-1] > max(y):
    y_ticks = y_ticks[-1:]

ax1.set_yticks(y_ticks, [str(i) for i in y_ticks])

# un-comment out the following line to have your labels 
# not in scientific notation
# ax1.get_yaxis().set_major_formatter(mpl.ticker.ScalarFormatter())

plt.show()

推荐阅读