简体   繁体   English

如何在 Python 图中以弧度设置 y 轴?

[英]How can I set the y axis in radians in a Python plot?

I would like to write the radian units of the axes as proportional to \\pi : something like我想写轴的弧度单位与\\pi成正比:类似

$\frac{\pi}{4}$, $\frac{\pi}{2}$, ... 

in place of代替

0.785, 1.5707 ... 

Is there any standard way?有没有标准的方法? As an example, what should I add to the following code?例如,我应该在下面的代码中添加什么?

from pylab import *

x=arange(-10.0,10.0,0.1)
y= arctan(x)

plot(x,y,'b.')
show()

I found this example http://matplotlib.sourceforge.net/examples/units/radian_demo.html but it does not work because I don't have basic_units module.我发现这个例子http://matplotlib.sourceforge.net/examples/units/radian_demo.html但它不起作用,因为我没有 basic_units 模块。

Thank you!谢谢!

hard code them in fractions or accept floating numbers将它们硬编码为分数或接受浮点数

import matplotlib.pyplot as plt
import numpy as np

x=np.arange(-10.0,10.0,0.1)
y=np.arctan(x)

fig = plt.figure()
ax  = fig.add_subplot(111)

ax.plot(x,y,'b.')

y_pi   = y/np.pi
unit   = 0.25
y_tick = np.arange(-0.5, 0.5+unit, unit)

y_label = [r"$-\frac{\pi}{2}$", r"$-\frac{\pi}{4}$", r"$0$", r"$+\frac{\pi}{4}$",   r"$+\frac{\pi}{2}$"]
ax.set_yticks(y_tick*np.pi)
ax.set_yticklabels(y_label, fontsize=20)

y_label2 = [r"$" + format(r, ".2g")+ r"\pi$" for r in y_tick]
ax2 = ax.twinx()
ax2.set_yticks(y_tick*np.pi)
ax2.set_yticklabels(y_label2, fontsize=20)

plt.show()

the result is结果是

在此处输入图片说明

i wrote a little function, that gives you back a list of labels:我写了一个小函数,它会给你一个标签列表:

import numpy as np
from fractions import Fraction

def create_pi_labels(a, b, step):

    max_denominator = int(1/step)
    # i added this line and the .limit_denominator to solve an 
    # issue with floating point precision
    # because of floataing point precision Fraction(1/3) would be 
    # Fraction(6004799503160661, 18014398509481984)

    values = np.arange(a, b+step/10, step)
    fracs = [Fraction(x).limit_denominator(max_denominator) for x in values]
    ticks = values*np.pi

    labels = []

    for frac in fracs:
        if frac.numerator==0:
            labels.append(r"$0$")
        elif frac.numerator<0:
            if frac.denominator==1 and abs(frac.numerator)==1:
                labels.append(r"$-\pi$")
            elif frac.denominator==1:
                labels.append(r"$-{}\pi$".format(abs(frac.numerator)))
            else:
                labels.append(r"$-\frac{{{}}}{{{}}} \pi$".format(abs(frac.numerator), frac.denominator))
        else:
            if frac.denominator==1 and frac.numerator==1:
                labels.append(r"$\pi$")
            elif frac.denominator==1:
                labels.append(r"${}\pi$".format(frac.numerator))
            else:
                labels.append(r"$\frac{{{}}}{{{}}} \pi$".format(frac.numerator, frac.denominator))

    return ticks, labels

https://github.com/MaxNoe/python-plotting/blob/master/source/create_pi_labels.py https://github.com/MaxNoe/python-plotting/blob/master/source/create_pi_labels.py

You can download the basic_units.py file here :您可以在此处下载 basic_units.py 文件:

After it should work like this:之后它应该像这样工作:

from pylab import *
from basic_units import radians

x = arange(-10.0,10.0,0.1)
y = map(lambda y: y*radians,arctan(x))
x = map(lambda x: x*radians,x)

plot(x,y,'b.',xunits=radians,yunits=radians)
show()

Alternatively you could implement the arctan function the way they implemented the cos function in basic_units.py或者,您可以按照他们在 basic_units.py 中实现 cos 函数的方式实现 arctan 函数

I created a PyPi Package that can format and place ticks at multiples of fractions of pi.我创建了一个PyPi 包,它可以在 pi 的分数的倍数上格式化和放置刻度。

"""Show an example of using MultiplePi on the y-axis."""
import matplotlib.pyplot as plt
import numpy as np

from matplot_fmt_pi import MultiplePi

x = np.arange(-10.0, 10.0, 0.1)
y = np.arctan(x)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.set_title("MultiplePi formatting")
ax.plot(x, y, 'b.')

y_pi = y / np.pi
unit = 0.25
y_tick = np.arange(-0.5, 0.5 + unit, unit)

# New way
manager = MultiplePi(4)
ax.yaxis.set_major_locator(manager.locator())
ax.yaxis.set_major_formatter(manager.formatter())

# Other way
y_label2 = [r"$" + format(r, ".2g") + r"\pi$" for r in y_tick]
ax2 = ax.twinx()
ax2.set_yticks(y_tick * np.pi)
ax2.set_yticklabels(y_label2)

plt.savefig("./pi_y_axis.png", dpi=120)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中更改直方图 Y 轴上的值 - How can I change the values on Y axis of Histogram plot in Python 如何在 python 中以像素数为 x 轴,灰度颜色为 y 轴 plot 图形? - How can I plot the figure with the number of pixel as a x-axis and the grayscale color as a y-axis in python? 如何使用 Python 将弧度转换为度数? - How can I convert radians to degrees with Python? 如何正确设置网格图的 y 轴,以免弄脏? - How can I set the y axis of the Trellis plot properly so it is not smudged? 如何在 y 轴不基于计数的 Python 中创建堆叠条形图 plot - How can I create a Stacked Bar plot in Python where the y axis is NOT based on counts 如何创建 y 轴上的值列表,而不必在 Python 中创建 plot 图形? - How can I create a list of the values on the y-axis without having to plot a graph in Python? 在 python - 我如何 plot 2D 图(x,y)并通过每个(x,y)坐标的颜色变化添加第三轴? - In python - How can I plot 2D figure (x,y) and add 3rd axis by variation of the colour for each (x,y)-coordinate? 如何使用python显式绘制y轴 - how to explicitly plot y axis with python 如何在 Python 中有效地将度角转换为弧度? - How can I convert a degrees angle to radians effectively in Python? 如何在 yellowbrick plot 中标记 X 轴和 Y 轴? 我使用的代码如下所示 - How can I labeled the X axis and Y axis in yellowbrick plot? The code is I used is show below
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM