如何将*all*matplotlib极轴角度标签的格式设置为以pi和弧度表示?

2024-04-19 13:06:47 发布

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

这不是thisthis的重复,因为我的问题的答案一点都不满意,我不想处理这个每个标签。这也不是this的副本,因为它不处理我的特定问题。在

我想设置极坐标图的角轴标签,不是一个接一个,而是通过一个时间初始化方法。这必须是可能的,因为似乎有其他轴类型相似的方法。在


Tags: 方法答案类型时间副本标签this极坐标
1条回答
网友
1楼 · 发布于 2024-04-19 13:06:47

我以前就知道怎么做,但汉顿在这里没有看到完全相同的问题,这里也没有找到好的解决办法。虽然我不确定这是否是最好的方法,但它肯定比设置每个标签的格式要好!在

所以我找到的解决方案是使用FunctionFormatter。定义很短,所以我就粘贴在这里。在

class FuncFormatter(Formatter):
    """
    Use a user-defined function for formatting.

    The function should take in two inputs (a tick value ``x`` and a
    position ``pos``), and return a string containing the corresponding
    tick label.
    """
    def __init__(self, func):
        self.func = func

    def __call__(self, x, pos=None):
        """
        Return the value of the user defined function.

        `x` and `pos` are passed through as-is.
        """
        return self.func(x, pos)

这个格式化程序类将允许我们创建一个函数,并将其作为参数传递,该函数的输出将是我们的绘图角度标签的格式。在

然后,可以使用PolarAxis.xaxis.set_major_formatter(formatter)来使用新创建的格式化程序,并且只更改角度轴标签。同样的事情可以用yaxis属性来代替,并且会导致内部的径向标签也发生变化。在

下面是我们要传递的函数:

^{pr2}$

它使用标准的python格式字符串作为输出,去掉不必要的小数,并在字符串的末尾附加pi符号,以保持它的pi形式。在

整个程序如下所示:

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import math

def radian_function(x, pos =None):
    # the function formatter sends
    rad_x = x/math.pi
    return "{}π".format(str(rad_x if rad_x % 1 else int(rad_x)))

ax = plt.subplot(111, projection='polar')
ax.set_rmax(4)
ax.set_rticks([1, 2, 3, 4])
ax.grid(True)
ax.set_title("Polar axis label example", va='bottom')

# sets the formatter for the entire set of angular axis labels
ax.xaxis.set_major_formatter(ticker.FuncFormatter(radian_function))
# sets the formatter for the radius inner labels.
#ax.yaxis.set_major_formatter(ticker.FuncFormatter(radian_function))
plt.show()

哪些输出

enter image description here

您可以进一步改进格式化程序以检查一个(这样简单地显示为π),或者以类似的方式检查0。您甚至可以使用position变量(我省略了它,因为它是不必要的)来进一步改进视觉格式。在

这样的函数可能如下所示:

def radian_function(x, pos =None):
    # the function formatter sends
    rad_x = x/math.pi
    if rad_x == 0:
        return "0"
    elif rad_x == 1:
        return "π"
    return "{}π".format(str(rad_x if rad_x % 1 else int(rad_x)))

相关问题 更多 >