Aspect ratio in semi-log plot with Matplotlib

≡放荡痞女 提交于 2021-02-04 18:55:51

问题


When I plot a function in matplotlib, the plot is framed by a rectangle. I want the ratio of the length and height of this rectangle to be given by the golden mean ,i.e., dx/dy=1.618033...

If the x and y scale are linear I found this solution using google

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')

If it is a log-log plot I came up with this solution

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')

However, for a semi-log plot, when I call set_aspect, I get

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

Can anyone think of a work-around for this?


回答1:


the most simple solution would be to log your data and then use the method for lin-lin.

you can then label the axes to let it look like a normal log-plot.

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

pl.yticks(ticks, ticklabels)

if you have higher values than 10e9 you will need three pairs of braces, two pairs for the LaTeX braces and one for the .format()

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

Edit: if you want also the ticks for 0.1ex ... 0.9ex, you want to use the minor ticks as well: they need to be located at log10(1), log10(2), log10(3) ..., log10(10), log10(20) ...

you can create and set them with:

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)


来源:https://stackoverflow.com/questions/24866419/aspect-ratio-in-semi-log-plot-with-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!