python - matplotlib - 带有角度标签的极坐标图

时间:2014-01-16 20:31:12

标签: python numpy matplotlib polar-coordinates

我遇到的问题看起来很简单:无论何时我做极坐标图,角度刻度由ThetaFormatter处理,它以度数标记它们。

我知道这个question,其中ticks标签被风玫瑰名称取代,而example看起来像matplotlib在笛卡尔环境中做了我想要的东西,但是我没有我发现如何在极地情节中做同样的事情......这将是最自然的!

以下是极地情节的一些简单示例:

from pylab import *
fig = figure()
axe = fig.gca(polar=True)
thetas = linspace(0,2*pi,200)
rhos = 3+cos(5*thetas)
axe.plot(thetas, rhos)
fig.show()

2 个答案:

答案 0 :(得分:4)

这应该这样做:

>>> fig=plt.figure()
>>> axe=fig.gca(polar=True)
>>> thetas=linspace(0,2*pi,200)
>>> rhos=3+cos(5*thetas)
>>> axe.plot(thetas, rhos)
[<matplotlib.lines.Line2D object at 0x109a2b550>]
>>> xT=plt.xticks()[0]
>>> xL=['0',r'$\frac{\pi}{4}$',r'$\frac{\pi}{2}$',r'$\frac{3\pi}{4}$',\
    r'$\pi$',r'$\frac{5\pi}{4}$',r'$\frac{3\pi}{2}$',r'$\frac{7\pi}{4}$']
>>> plt.xticks(xT, xL)
([<matplotlib.axis.XTick object at 0x107bac490>, <matplotlib.axis.XTick object at 0x109a31310>, <matplotlib.axis.XTick object at 0x109a313d0>, <matplotlib.axis.XTick object at 0x109a31050>, <matplotlib.axis.XTick object at 0x1097a8690>, <matplotlib.axis.XTick object at 0x1097a8cd0>, <matplotlib.axis.XTick object at 0x1097a8150>, <matplotlib.axis.XTick object at 0x107bb8fd0>], <a list of 8 Text xticklabel objects>)
>>> plt.show()

enter image description here

答案 1 :(得分:0)

使用python 3.8.3和matplotlib 3.2.2,可以通过get_xticks(以十进制弧度返回刻度值)和set_xticklabels函数来巧妙地实现这一点。

如果您希望使用其他标签样式(例如,十进制弧度或精度不同),则可以将format_radians_label函数替换为任何带浮点数(以弧度为单位)并返回相应字符串的函数。

为了避免使用TeX格式化程序,我直接使用了UTF8字符π而不是\pi

import matplotlib.pyplot as plt
import numpy as np

def format_radians_label(float_in):
    # Converts a float value in radians into a
    # string representation of that float
    string_out = str(float_in / (np.pi))+"π"
    
    return string_out

def convert_polar_xticks_to_radians(ax):
    # Converts x-tick labels from degrees to radians
    
    # Get the x-tick positions (returns in radians)
    label_positions = ax.get_xticks()
    
    # Convert to a list since we want to change the type of the elements
    labels = list(label_positions)
    
    # Format each label (edit this function however you'd like)
    labels = [format_radians_label(label) for label in labels]
    
    ax.set_xticklabels(labels)

fig = plt.figure()
axe = fig.gca(polar=True)
thetas = np.linspace(0,2*np.pi,200)
rhos = 3+np.cos(5*thetas)
axe.plot(thetas, rhos)

convert_polar_xticks_to_radians(axe)

fig.show()

Polar plot with radians for xticks