首页 > 解决方案 > 是否可以在 matplotlib 的辅助轴上手动设置刻度?

问题描述

我正在尝试绘制一个由函数链接的两个 x 轴和两个 y 轴的图形,我使用以下代码实现了这一点:

import numpy as np
import matplotlib.pyplot as plt

def q2r(q):
    return(2*np.pi)/q
def r2q(r):
    return(2*np.pi)/r

def w2t(w):
    tau = 1/w
    return(tau*(2/0.6583))
def t2w(t):
    tau = t/(2/0.6583)
    return(1/tau)

x = np.linspace(1,10)
y = x**2

fig, axs = plt.subplots(subplot_kw = {'xlabel':'$\omega / meV$', 'ylabel':'Q / $\AA^{-1}$'})
axs.plot(x,y)
secax_x = axs.secondary_xaxis('top', xlabel='t / ps', functions = (w2t, t2w))
secax_y = axs.secondary_yaxis('right', ylabel = 'r / $\AA$', functions = (q2r, r2q))

# sets ticks on primary axes
axs.set_xticks([2,5,8])
axs.set_yticks([20,50,80])

# does nothing
secax_x.set_xticks([3,1,0.5,0.1])
secax_y.set_yticks([1,0.2,0.01])

plt.show()

示例图

因为主轴和次轴之间的关系不是线性的,所以次轴上的刻度被挤压在一起(例如 x2 上)或太少(例如 y2 上)。我不希望刻度值相等,但希望手动控制辅助轴上的刻度位置。是否有可能做到这一点?

标签: pythonmatplotlib

解决方案


推荐阅读