Skip to main content
 首页 » 编程设计

python之在 matplotlib 中对大记录值使用对数刻度而不会溢出

2024年11月24日8JeffreyZhao

如何为已经记录但太大而无法取幂回到线性刻度的值设置对数刻度?示例:

import matplotlib.pylab as plt 
import numpy as np 
 
def f_returns_verylarge_logs(): 
    # some computation here that returns very small numbers on a log scale 
    # (meaning large negative numbers in log units) 
    log10_y = [3000, 3100, 3200] 
    return log10_y 
 
ax1 = plt.subplot(2, 1, 1) 
x = [1, 2, 3] 
# y values are small, so it is no problem to keep them 
# around in LINEAR scale 
y = [50, 100, 200] 
plt.plot(x, y) 
plt.xlabel("x") 
plt.ylabel("y") 
ax1.set(yscale="log") 
ax2 = plt.subplot(2, 1, 2) 
x = [1, 2, 3] 
log_y = f_returns_verylarge_logs() 
y = np.power(10., log_y)  
plt.plot(x, y) 
plt.xlabel("x") 
plt.ylabel("y") 
ax2.set(yscale="log") 
plt.show() 

这会产生溢出错误:

RuntimeWarning: overflow encountered in power 
  y = np.power(10., log_y) 

我们的目标是让底部绘图工作并且看起来(在 yticks/标签方面)像顶部没有取消记录 log_y 因为它会导致溢出。

一个糟糕的解决方案是缩小日志值然后取消记录它们,如下所示:

plt.figure() 
scaled_log_y = np.array(log_y) / 100. 
scaled_unlog_y = np.power(10., scaled_log_y) 
plt.plot(x, scaled_unlog_y) 
plt.gca().set(yscale="log") 
plt.ylabel("y (units are wrong)") 
plt.xlabel("x") 
plt.show() 

但这给出了错误的单位:对于 3000,它说的是 10^30 而不是 10^3000。

请您参考如下方法:

可能您想要类似下面的内容,其中位置 n 的每个刻度都简单地标记为 "10^n"。

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.ticker as mticker 
 
x = [1, 2, 3] 
y1 = [50, 100, 200] 
y2 = [3000, 3100, 3200] 
 
ax1 = plt.subplot(2, 1, 1) 
ax1.plot(x, y1) 
ax1.set_xlabel("x") 
ax1.set_ylabel("y") 
ax1.set(yscale="log") 
 
ax2 = plt.subplot(2, 1, 2) 
 
ax2.plot(x, y2) 
ax2.set_xlabel("x") 
ax2.set_ylabel("y") 
ax2.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x,_: f"$10^{{{int(x)}}}$")) 
 
plt.show()