如何将 y 轴比例因子移动到 y 轴标签旁边的位置? [英] How to move the y axis scale factor to the position next to the y axis label?

查看:21
本文介绍了如何将 y 轴比例因子移动到 y 轴标签旁边的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绘制了一些数据,我将这些数据强制为 10 的幂(而不是指数)的科学记数法.下面是代码片段:

I have some data plotted which I force to scientific notation to powers of 10 (instead of exponential). Heres a snippet of the code:

import matplotlib.ticker as mticker

formatter = mticker.ScalarFormatter(useMathText=True)
formatter.set_powerlimits((-3,2))
ax.yaxis.set_major_formatter(formatter)

但是,x10^-4 的比例因子出现在图表的左上角.

However, the scale factor of x10^-4 appears on the top left hand corner of the graph.

是否有一种简单的方法可以强制将此比例因子的位置放在 y 标签旁边,如下图所示?

Is there a simple method to force the position of this scale factor next to the y label as I have illustrated in the diagram below?

推荐答案

您可以将偏移设置为不可见,这样它就不会出现在其原始位置.

You may set the offset to invisible, such that it does not appear in its original position.

ax.yaxis.offsetText.set_visible(False)

然后您可以从格式化程序中获取偏移量并用它更新标签

You may then get the offset from the formatter an update the label with it

offset = ax.yaxis.get_major_formatter().get_offset()
ax.yaxis.set_label_text("original label" + " " + offset)

这样它就会出现在标签内.

such that it appears inside the label.

以下使用带有回调的类自动执行此操作,以便如果偏移量发生变化,它将在标签中更新.

The following automates this using a class with a callback, such that if the offset changes, it will be updated in the label.

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

class Labeloffset():
    def __init__(self,  ax, label="", axis="y"):
        self.axis = {"y":ax.yaxis, "x":ax.xaxis}[axis]
        self.label=label
        ax.callbacks.connect(axis+'lim_changed', self.update)
        ax.figure.canvas.draw()
        self.update(None)

    def update(self, lim):
        fmt = self.axis.get_major_formatter()
        self.axis.offsetText.set_visible(False)
        self.axis.set_label_text(self.label + " "+ fmt.get_offset() )


x = np.arange(5)
y = np.exp(x)*1e-6

fig, ax = plt.subplots()
ax.plot(x,y, marker="d")

formatter = mticker.ScalarFormatter(useMathText=True)
formatter.set_powerlimits((-3,2))
ax.yaxis.set_major_formatter(formatter)

lo = Labeloffset(ax, label="my label", axis="y")


plt.show()

这篇关于如何将 y 轴比例因子移动到 y 轴标签旁边的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆