我有我想显示两种不同尺度的数据。Matplotlib 文档(例如this one)包含一些示例,它们将 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)
此代码生成下图,显示没有小刻度。
你的小刻度被你的大刻度隐藏了。
axj.set_xscale('log', basex=2)
axj.set_yscale('log', basey=2)
将“双轴”的刻度设置为对数,因此使用对数大刻度 ( 4, 16, 64, 256, 1024
)。
axj.xaxis.set_minor_locator(ticker.LogLocator(base=2))
axj.yaxis.set_minor_locator(ticker.LogLocator(base=2))
这将在对数位置添加小刻度4, 16, 64, 256, 1024
;与您的主要刻度相同。
你想要做的是:
axi.xaxis.set_minor_locator(ticker.LogLocator(base=2))
axi.yaxis.set_minor_locator(ticker.LogLocator(base=2))
向您的线性轴添加次要对数刻度,或:
axj.xaxis.set_minor_locator(ticker.LinearLocator())
axj.yaxis.set_minor_locator(ticker.LinearLocator())
向对数轴添加较小的线性刻度。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句