Matplotlib:绘制两个x轴,一个是线性轴,一个是对数刻度轴

2024-10-08 23:18:50 发布

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

(大量编辑:)

在python matplotlib中,我想用两个xscale来绘制y与{}的对比,下一个使用线性刻度,而上面的用对数刻度。在

较低的x值是上面值的一个任意函数(在本例中,映射是func(x)=np.log10(1.0+x))。推论:上面的x记号位置与下面的位置是相同的任意函数。在

两个轴的数据点位置和刻度位置必须解耦。在

我希望上轴的对数刻度位置和标签尽可能整齐。在

制作这样一个情节的最佳方式是什么?在

相关:http://matplotlib.1069221.n5.nabble.com/Two-y-axis-with-twinx-only-one-of-them-logscale-td18255.html

类似(但未回答)的问题?:Matplotlib: how to set ticks of twinned axis in log plot

可能有用:https://stackoverflow.com/a/29592508/1021819


Tags: of函数com编辑matplotlibnp绘制对数
2条回答

您可能会发现^{}和{a2}很有用。在

import numpy as np
import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

x = np.arange(0.01, 10.0, 0.01) # x-axis range
y = np.sin(2*np.pi*x) # simulated signal to plot

ax1.plot(x, y, color="r") # regular plot (red)
ax1.set_xlabel('x')

ax2 = ax1.twiny() # ax1 and ax2 share y-axis
ax2.semilogx(x, y, color="b") # semilog plot (blue)
ax2.set_xlabel('semilogx')

plt.show()

这里是一个尝试回答后,与一些人交谈,并感谢@BusyBeaver。在

我同意这个问题是不恰当的,我会修改它以澄清(欢迎大家!)。在

我确实认为写在stackoverflow上很有用。在

代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator

# Necessary functions

def tick_function(x):
    """Specify tick format"""
    return ["%2.f" % i for i in x]

def func(x):
    """This can be anything you like"""
    funcx=np.log10(1.0+x)
    return funcx

z=np.linspace(0.0,4.0,20)

np.random.seed(seed=1234)
y=np.random.normal(10.0,1.0,len(z))

# Set up the plot
fig,ax1 = subplots()
ax1.xaxis.set_minor_locator(AutoMinorLocator())
ax1.yaxis.set_minor_locator(AutoMinorLocator())

# Set up the second axis
ax2 = ax1.twiny()

# The tick positions can be at arbitrary positions
zticks=np.arange(z[0],z[-1]+1)
ax2.set_xticks(func(zticks))
ax2.set_xticklabels(tick_function(zticks))
ax2.set_xlim(func(z[0]),func(z[-1]))
ax1.set_ylim(5.0,15.0)

ax1.set_xlabel(r'$\log_{10}\left(1+z\right)$')
ax2.set_xlabel(r'$z$')
ax1.set_ylabel('amplitude/arb. units')

plt.tick_params(axis='both',which = 'major', labelsize=8, width=2)
plt.tick_params(axis='both',which = 'minor', labelsize=8, width=1)

_=ax1.plot(func(z),y,'k.')

plt.savefig('lnopz2.png')

Plot generated from the above code

我不知道如何控制ax2小刻度上限(例如,每0.5次)。在

相关问题 更多 >

    热门问题