Matplotlib loglog plot仅显示y轴上的十次幂

2024-04-27 04:42:39 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下代码:

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

结果如下:

enter image description here

我想做的是删除y轴上不是10次方的记号。在此特定示例中,移除9x10^-3、8x10^-3等,仅保留10^-2

我试过其他一些建议,例如:{a2},但没有一个奏效。。 有什么想法吗


Tags: 代码fromimportlogplotmatplotlibasfig
1条回答
网友
1楼 · 发布于 2024-04-27 04:42:39

您可以找到最小和最大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()

相关问题 更多 >