首页 > 解决方案 > 在对数图中修复 x 轴和 y 轴 python

问题描述

我想要 x 轴和 y 轴

情节 1

看起来像那些

情节 2

下面的代码来自我用来显示数据的 python 脚本。我正在使用 python 3.9.5。

日志轴显示如下[1x10^-4, 2x10^-4],我希望它们看起来像[1, 2] x 10^-4.

plt.figure(1) 
plt.plot( timeA, testA, label='P' )  
plt.plot( timeA, meanA, label='meanP')
plt.legend() 
plt.xlabel('Time')
plt.ylabel('P') 
plt.yscale('log')
plt.xscale('log')

标签: pythonmatplotlib

解决方案


使用 ScalarFormatter 控制指数显示并更改刻度设置。请参阅此页面了解更多信息

import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

x = np.linspace(620000,680000,200)
step = np.random.choice([-1500,1500],200)
y = np.cumsum(step)

fig, ax = plt.subplots()

ax.plot(x, y, label='P' )  
ax.plot(x, [np.mean(y)]*len(y), label='meanP')
ax.legend() 
ax.set_xlabel('Time')
ax.set_ylabel('P') 

ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
ax.xaxis.set_major_formatter(ScalarFormatter(useMathText=True))
ax.ticklabel_format(style="sci",  axis="both", scilimits=(0,0))

plt.show()

在此处输入图像描述


推荐阅读