python – 使用Matplotlib的半对数图中的宽高比

当我在matplotlib中绘制函数时,绘图由矩形框起.我希望这个矩形的长度和高度的比率由黄金均值给出,即,dx / dy = 1.618033 ……

如果x和y标度是线性的,我使用谷歌找到了这个解决方案

import numpy as np
import matplotlib.pyplot as pl
golden_mean = (np.sqrt(5)-1.0)/2.0
dy=pl.gca().get_ylim()[1]-pl.gca().get_ylim()[0]
dx=pl.gca().get_xlim()[1]-pl.gca().get_xlim()[0]
pl.gca().set_aspect((dx/dy)*golden_mean,adjustable='box')

如果是对数日志图,我想出了这个解决方案

dy=np.abs(np.log10(pl.gca().get_ylim()[1])-np.log10(pl.gca().get_ylim()[0]))
dx=np.abs(np.log10(pl.gca().get_xlim()[1])-np.log10(pl.gca().get_xlim()[0]))
pl.gca().set_aspect((dx/dy)*golden_mean,adjustable='box')

但是,对于半对数图,当我调用set_aspect时,我得到了

UserWarning: aspect is not supported for Axes with xscale=log, yscale=linear

任何人都可以想到解决这个问题吗?

最佳答案 最简单的解决方案是记录您的数据,然后使用lin-lin的方法.

然后,您可以标记轴,使其看起来像正常的对数图.

ticks = np.arange(min_logx, max_logx, 1)
ticklabels = [r"$10^{}$".format(tick) for tick in ticks]

pl.yticks(ticks, ticklabels)

如果您的值高于10e9,则需要三对括号,两对用于LaTeX括号,一对用于.format()

ticklabels = [r"$10^{{{}}}$".format(tick) for tick in ticks]

编辑:
如果你还需要0.1ex … 0.9ex的刻度,你也想要使用次刻度:
它们需要位于log10(1),log10(2),log10(3)……,log10(10),log10(20)……

你可以创建和设置它们:

minor_ticks = []
for i in range(min_exponent, max_exponent):
    for j in range(2,10):
         minor_ticks.append(i+np.log10(j))


plt.gca().set_yticks(minor_labels, minor=True)
点赞