import numpy as np import matplotlib.pyplot as plt
c=3.1
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
xticks0 = np.array([1, 1.03, 1.2, 1.5, 2.06, 3.1, 6.2, 15.5], dtype = 'int_')
xvals = np.arange(3, 16, 0.00001)
data = xvals
ax1.plot(xvals, data)
ax1Ticks =xvals
ax2Ticks = xticks0
def tick_function(X):
V = c/X
return ["%.2f" % z for z in V]
ax2.set_xticks(ax2Ticks)
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels(tick_function(ax2Ticks))
ax1.set_xlabel("harmonic order")
ax2.set_xlabel('Wavelength (micrometer)')
ax1.grid(True)
plt.xlim(xmin=3, xmax=15)
plt.tick_params(labelsize = 12 );
plt.show()
我想在顶轴上放置特定的刻度线
但是,没有显示。
我想要的是
底轴3~15阵列
上轴3.1/下轴(3,2.5,2,1.5,1,0.5,0.2)。
如果我理解正确,您想在顶部添加一个单独的刻度和一些自定义标签。
这是您可以做到的方法
tick_function
将添加自定义标签这是可以提供帮助的代码部分:
ax2 = ax1.twiny() # Secondary (top) axis
ax2_ticks = np.array([1, 1.03, 1.2, 1.5, 2.06, 3.1, 6.2, 15.5])
ax2_labels = [f"{x:.2f}" for x in ax2_ticks]
ax2.set_xticks(ax2_ticks)
ax2.set_xticklabels(ax2_labels)
ax2.set_xlabel("Top Axis: Wavelength (micrometer)")
在这里我修复了整个代码,似乎这是必要的:
import numpy as np
import matplotlib.pyplot as plt
# Constants
c = 3.1
xvals = np.arange(3, 20, 0.00001) # Primary axis values
fig, ax1 = plt.subplots(figsize=(12, 10)) # Primary axis (bottom)
ax2 = ax1.twiny() # Secondary (top) axis
ax1_ticks = np.arange(3, 16)
ax1.set_xticks(ax1_ticks)
ax1.set_xticklabels(ax1_ticks)
ax1.set_xlabel("Botton Axis: Harmonic Order")
ax2_ticks = np.array([1, 1.03, 1.2, 1.5, 2.06, 3.1, 6.2, 15.5])
ax2_labels = [f"{x:.2f}" for x in ax2_ticks]
ax2.set_xticks(ax2_ticks)
ax2.set_xticklabels(ax2_labels)
ax2.set_xlabel("Top Axis: Wavelength (micrometer)")
ax1.set_xlim(3, 16)
ax2.set_xbound(ax1.get_xbound())
# Add if you need vertical lines
ax1.grid(True, which='both', axis='x')
ax2.grid(True, which='both', axis='x')
ax1.plot(xvals, xvals)
plt.show()