2017-06-20 7 views
0

これはthisまたはthisの複製ではありません。私の問題ではそれほど満足のいくものではなかったので、につきましてはに対処したくありません。これは私の特定の問題に対処していないので、thisの複製でもありません。* all * matplotlibの極座標の角度ラベルのフォーマットをπとラジアンで設定する方法は?

極性プロットの角軸ラベルを1つずつではなく、1回の初期化メソッドで設定したいとします。他の軸タイプと同様のものへの道があるように思われるので、これは可能でなければなりません。

答えて

0

私は手でこれを行う方法を知っていましたが、ここで全く同じ質問は見られませんでした。良い解決策もここでは見つかりませんでした。これが最善の方法であるかどうかはわかりませんが、ラベルごとのフォーマットを設定するよりも確かに優れています!

私が見つけた解決策は、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属性で同じことを行うことができ、内側の放射状のラベルも同様に変更されます。不要な小数を取り除く、

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))) 

それが出力として標準のPythonのフォーマット文字列を使用し、文字列の最後までにパイ記号を追加:ここで

は、我々の関数はそのように見えるもの、我々が通過しますですπの点でそれを保つ。

完全なプログラムは次のようになります。

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

を出力するあなたは、さらに(は単にπとして示されているように)1をチェックするフォーマッタを改善したりでき同様の方法で0をチェックしてください。ビジュアルフォーマットをさらに改善するために、位置変数(これは不要だったので省略した)を使用することもできます。

、このような機能は、次のようになります。

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))) 
関連する問題