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)
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()
我以前就知道怎么做,但汉顿在这里没有看到完全相同的问题,这里也没有找到好的解决办法。虽然我不确定这是否是最好的方法,但它肯定比设置每个标签的格式要好!在
所以我找到的解决方案是使用FunctionFormatter。定义很短,所以我就粘贴在这里。在
这个格式化程序类将允许我们创建一个函数,并将其作为参数传递,该函数的输出将是我们的绘图角度标签的格式。在
然后,可以使用
PolarAxis.xaxis.set_major_formatter(formatter)
来使用新创建的格式化程序,并且只更改角度轴标签。同样的事情可以用yaxis
属性来代替,并且会导致内部的径向标签也发生变化。在下面是我们要传递的函数:
^{pr2}$它使用标准的python格式字符串作为输出,去掉不必要的小数,并在字符串的末尾附加pi符号,以保持它的pi形式。在
整个程序如下所示:
哪些输出
您可以进一步改进格式化程序以检查一个(这样
1π
简单地显示为π
),或者以类似的方式检查0。您甚至可以使用position变量(我省略了它,因为它是不必要的)来进一步改进视觉格式。在这样的函数可能如下所示:
相关问题 更多 >
编程相关推荐