gpt4 book ai didi

Matplotlib loglog 的错误刻度/标签(双轴)

转载 作者:行者123 更新时间:2023-12-02 03:42:23 32 4
gpt4 key购买 nike

我正在使用 matplotlib 创建对数对数图。如下图所示,默认刻度选择不当(充其量);右边的 y 轴甚至根本没有任何东西(它在线性等效中有)并且两个 x 轴都只有一个。

loglog plot with bad default ticks

有没有办法通过标签获得合理数量的刻度,无需为每个绘图手动指定它们?


编辑:确切的代码太长,但这里有一个简短的问题示例:

x = linspace(4, 18, 20)
y = 1 / (x ** 4)
fig = figure()
ax = fig.add_axes([.1, .1, .8, .8])
ax.loglog(x, y)
ax.set_xlim([4, 18])
ax2 = ax.twiny()
ax2.set_xlim([4 / 3., 18 / 3.])
ax2.set_xscale('log')
show()

最佳答案

我一直在与您展示的内容作斗争(轴范围内只有一个主要刻度)。没有一个 matplotlib 刻度格式化程序让我满意,所以我使用 matplotlib.ticker.FuncFormatter 来实现我想要的。我没有用双轴进行测试,但我的感觉是无论如何它都应该可以工作。

import matplotlib.pyplot as plt
from matplotlib import ticker
import numpy as np

#@Mark: thanks for the suggestion :D
mi, ma, conv = 4, 8, 1./3.
x = np.linspace(mi, ma, 20)
y = 1 / (x ** 4)

fig, ax = plt.subplots()

ax.plot(x, y) # plot the lines
ax.set_xscale('log') #convert to log
ax.set_yscale('log')

ax.set_xlim([0.2, 1.8]) #large enough, but should show only 1 tick

def ticks_format(value, index):
"""
This function decompose value in base*10^{exp} and return a latex string.
If 0<=value<99: return the value as it is.
if 0.1<value<0: returns as it is rounded to the first decimal
otherwise returns $base*10^{exp}$
I've designed the function to be use with values for which the decomposition
returns integers
"""
exp = np.floor(np.log10(value))
base = value/10**exp
if exp == 0 or exp == 1:
return '${0:d}$'.format(int(value))
if exp == -1:
return '${0:.1f}$'.format(value)
else:
return '${0:d}\\times10^{{{1:d}}}$'.format(int(base), int(exp))

# here specify which minor ticks per decate you want
# likely all of them give you a too crowed axis
subs = [1., 3., 6.]
# set the minor locators
ax.xaxis.set_minor_locator(ticker.LogLocator(subs=subs))
ax.yaxis.set_minor_locator(ticker.LogLocator(subs=subs))
# remove the tick labels for the major ticks:
# if not done they will be printed with the custom ones (you don't want it)
# plus you want to remove them to avoid font missmatch: the above function
# returns latex string, and I don't know how matplotlib does exponents in labels
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.yaxis.set_major_formatter(ticker.NullFormatter())
# set the desired minor tick labels using the above function
ax.xaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format))
ax.yaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format))

我得到的数字如下enter image description here :

当然,您可以为 x 轴和 y 轴设置不同的次定位器,并且可以将从 ticks_format 到结尾的所有内容包装到接受轴实例 axsubssubsxsubsy 作为输入参数。

希望对你有帮助

关于Matplotlib loglog 的错误刻度/标签(双轴),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19239297/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com