【问题标题】:python 1/x plot scale formatting, tick positionpython 1/x 绘图比例格式,刻度位置
【发布时间】:2017-05-09 14:24:18
【问题描述】:

我用 Python 绘制了一些数据,并尝试用 FuncFormatter 更改刻度。现在我想将分段更改为整数。我还希望在同一结构中出现次要刻度,在我的情况下,它将是 1/x 分段。我希望缩放传播。这些图片将帮助您想象我的问题。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
x = np.array([805.92055,978.82006,564.88627,813.70311,605.73361,263.27184,169.40317])
y = np.array([10,9,8,7,6,3,2])
fig, ax = plt.subplots(figsize =(3.6,2.5))
plt.plot(1/x,y,linestyle ='None',marker='1')
a=0.001
b=0.005
plt.xlim(a,b)
def my_formatter_fun(x, p):
    return "%.0f" % (1/x)         
ax.get_xaxis().set_major_formatter(tick.FuncFormatter(my_formatter_fun))

如何更改分段以便得到这样的结果?我认为可以在my_formatter_fun 中添加我的愿望,但我不知道如何。我怎样才能在1/x 分布中添加次要刻度?我试过plt.minorticks_on() 但这不起作用,因为它们处于线性位置。

【问题讨论】:

    标签: python matplotlib plot scale ticker


    【解决方案1】:

    可以使用matplotlib.ticker.Locator 控制刻度的位置。对于1/x 滴答声,您需要定义自己的自定义定位器:

    class ReciprocalLocator(tick.Locator):
        def __init__(self, numticks = 5):
            self.numticks = numticks
        def __call__(self):
            vmin, vmax = self.axis.get_view_interval()
            ticklocs = np.reciprocal(np.linspace(1/vmax, 1/vmin, self.numticks))
            return self.raise_if_exceeds(ticklocs)
    

    你可以通过调用在你的情节中使用它

    ax.get_xaxis().set_major_locator(ReciprocalLocator(numticks=4))
    ax.get_xaxis().set_minor_locator(ReciprocalLocator(numticks=20))
    

    这需要更多调整才能将位置移动到合适的数字。如需灵感,请查看matplotlib.ticker.MaxNLocator的源代码。

    【讨论】:

      猜你喜欢
      • 2013-01-04
      • 2019-10-15
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      相关资源
      最近更新 更多