我有数据,我想显示两种不同的比例。Matplotlib 文档(例如这个文档)包含一些示例,它们包含 x 轴或 y 轴(不是两者),并且这些示例都没有显示如何在对数缩放时操纵 x 轴和 y 轴的小刻度。
这是我的问题:如何在双 x 轴和双 y 轴上格式化小刻度,这两个轴都是对数缩放的?在下面的示例中,传统的 xy 轴是线性缩放的(由下标表示i
),而交替/镜像/双 xy 轴是对数缩放的(由下标表示j
)。该功能是从一个类似的问题twinboth
中借来的。另外,我正在使用而不是,正如这篇文章中所建议的那样。LogLocator
AutoMinorLocator
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
## linear scale parameters
m, b = 0.5, np.pi
xi = np.arange(1, 11, 1).astype(int)
noisei = np.random.uniform(low=-0.5, high=0.5, size=xi.size)
yi = m * xi + b + noisei
## log scale parameters
xj = 2 ** xi
noisej = 2 ** noisei
yj = 2 ** yi
def twinboth(ax):
# Alternately, we could do `newax = ax._make_twin_axes(frameon=False)`
newax = ax.figure.add_subplot(ax.get_subplotspec(), frameon=False)
newax.xaxis.set(label_position='top')
newax.yaxis.set(label_position='right', offset_position='right')
newax.yaxis.get_label().set_rotation(-90) # Optional...
newax.yaxis.tick_right()
newax.xaxis.tick_top()
return newax
## initialize figure and linear axes
fig, axes = plt.subplots(nrows=2, ncols=2)
for axi in axes.ravel():
## plot linear
axi.scatter(xi, yi, color='r', alpha=0.5, label='linear')
axi.grid(color='k', alpha=0.3, linestyle=':')
## get twinned logarithmic axes
axj = twinboth(axi)
axj.set_xscale('log', basex=2)
axj.set_yscale('log', basey=2)
## whole number instead of sci-notation
axj.xaxis.set_major_formatter(ticker.ScalarFormatter())
axj.yaxis.set_major_formatter(ticker.ScalarFormatter())
## attempt log-scaled minor ticks on twin axes
axj.xaxis.set_minor_locator(ticker.LogLocator(base=2))
axj.yaxis.set_minor_locator(ticker.LogLocator(base=2))
axj.xaxis.set_minor_formatter(ticker.ScalarFormatter())
axj.yaxis.set_minor_formatter(ticker.ScalarFormatter())
## plot log-scale on twin axes
axj.scatter(xj, yj, color='b', alpha=0.5, label='log')
## get legend handles/labels from last iteration of for-loop above (avoid duplicates)
handlesi, labelsi = axi.get_legend_handles_labels()
handlesj, labelsj = axj.get_legend_handles_labels()
handles = handlesi + handlesj
labels = labelsi + labelsj
fig.subplots_adjust(bottom=0.2, wspace=0.3, hspace=0.3)
fig.legend(handles=handles, labels=labels, loc='lower center', mode='expand', ncol=2)
plt.show()
plt.close(fig)
此代码生成下图,显示没有次要刻度。