'liner'
),但你可以设置自定义的比例尺。这里有一些不错的示例。matplotlib.axes.Axes.set_xticks()
,或者matplotlib.axes.Axes.xaxis.set_major_locator()
。如果您使用网格,建议使用此方法。但由于我的知识有限,我希望能得到更详细的解释(因为现在我也对这个功能很好奇^^)现在来到棘手的部分:将刻度标签格式化为表示'2^x'
。我没有找到比将它们明确设置为字符串更好的方法。似乎只能在受限范围内更改通用格式,参见matplotlib.pyplot.ticklabel_format()
,其中可以选择是否以科学计数法显示(即在右下角显示'10^x'
)。如果有更通用的解决方案,请告诉我。
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import FixedLocator
# create dummy data
df = pd.DataFrame({
'x': [2**x for x in range(1,10)],
'y': list(range(1,10))
})
def forward(x):
return np.log2(x)
def inverse(x):
return 2**x
# open figure
fig, ax = plt.subplots(2,2)
axs = ax.flatten()
for i in range(0,4):
# plot data
axs[i].plot(df['x'],df['y'])
if i > 0:
# set scale function
axs[i].set_xscale('function', functions=(forward,inverse))
if i > 1:
# set ticks
# - OPTION 1
axs[i].set_xticks(df['x'])
# - OPTION 2
axs[i].xaxis.set_major_locator(FixedLocator(2**np.arange(1,10)))
if i > 2:
# est tick labels
axs[i].set_xticklabels( [f"2^{j:.0f}" for j in np.log2(df['x'])] )
plt.show()