Python Matplotlib:将轴设置为相对于一个值的增量

2024-10-01 22:33:36 发布

您现在位置:Python中文网/ 问答频道 /正文

有时当一个图被放大到足够大的时候,轴会发生变化,所以会显示出这样的情况

enter image description here

这意味着x值,在本例中是1.565+勾号中显示的值。在

有没有办法设置这种格式的轴刻度?在这里,我如何设置偏移量(在本例中是1.565)并格式化刻度?在


Tags: 格式情况偏移量办法刻度本例勾号轴会
1条回答
网友
1楼 · 发布于 2024-10-01 22:33:36

A、 手动放置偏移

我认为最简单的解决方案是绘制x-offset,而不是{}本身。然后只需添加一个文本字段,其偏移量低于轴。在

import numpy as np
import matplotlib.pyplot as plt

x = np.array([-0.02+np.pi/2, +0.02+np.pi/2])
y = [1,1]

plt.plot(x - np.pi/2, y)
plt.text(1, -0.07, "$+\pi / 2$", ha="right", va="top",
         transform=plt.gca().transAxes)

plt.show()

enter image description here

B、 使用固定格式设置工具

或者,您可以使用FixedFormatter并手动设置其偏移标签。在

^{pr2}$

enter image description here

这样做的缺点是,勾选位置是固定的,因此在缩放时会松开漂亮的标签。在

C、 使用具有固定偏移量的自定义定位器和格式化程序

这是可能的,但非常复杂。解决方案看起来类似于Set scientific notation with fixed exponent and significant digits for multiple subplots,但也需要使用定位器。在

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

class OffsetLocator(matplotlib.ticker.AutoLocator):
    def __init__(self, offset=0):
        self.fixed_offset = offset
        matplotlib.ticker.AutoLocator.__init__(self)
    def tick_values(self, vmin, vmax):
        v = np.array([vmin,vmax])-self.fixed_offset
        ticks = matplotlib.ticker.AutoLocator.tick_values(self, *v)
        return ticks + self.fixed_offset

class OffsetFormatter(matplotlib.ticker.ScalarFormatter):
    def __init__(self, offset=0, offsettext = None, mathText=True):
        self.fixed_offset = offset
        self.offset_text = offsettext
        matplotlib.ticker.ScalarFormatter.__init__(self,useOffset=offset,
                                                   useMathText=mathText)
    def _set_orderOfMagnitude(self, nothing):
        self.orderOfMagnitude = 0
    def _compute_offset(self):
        return self.fixed_offset
    def get_offset(self):
        return self.offset_text or matplotlib.ticker.ScalarFormatter.get_offset(self)


x = np.array([-0.02+np.pi/2, +0.02+np.pi/2])
y = [1,1]

plt.plot(x, y)

plt.gca().xaxis.set_major_locator(OffsetLocator(np.pi/2))
plt.gca().xaxis.set_major_formatter(OffsetFormatter(np.pi/2, offsettext="$+\pi / 2$"))

plt.show()

enter image description here

结果看起来与上述结果相似,但行为完全自然,就像在所有其他使用偏移量的情况下一样。人们可能只会在玩图形大小、缩放和平移等时观察到差异

相关问题 更多 >

    热门问题