如何以 pi 的倍数设置轴刻度(Python)(matplotlib) [英] How to set axis ticks in multiples of pi (Python) (matplotlib)

查看:20
本文介绍了如何以 pi 的倍数设置轴刻度(Python)(matplotlib)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 Python 绘制一个图,并以 pi 的倍数显示 x 范围的刻度.

有没有好的方法可以做到这一点,而不是手动?

我正在考虑使用 matplotlib,但其他选项也不错.

编辑 3:EL_DON 的解决方案对我来说是这样的:

导入 matplotlib.ticker 作为 tck导入 matplotlib.pyplot 作为 plt将 numpy 导入为 npf,ax=plt.subplots(figsize=(20,10))x=np.linspace(-10*np.pi, 10*np.pi,1000)y=np.sin(x)ax.plot(x/np.pi,y)ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $pi$'))ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))plt.style.use("ggplot")plt.show()

给予:

EDIT 2(在 EDIT 3 中解决!):EL_DON 的答案似乎不适合我:

导入 matplotlib.ticker 作为 tck导入 matplotlib.pyplot 作为 plt将 numpy 导入为 npf,ax=plt.subplots(figsize=(20,10))x=np.linspace(-10*np.pi, 10*np.pi)y=np.sin(x)ax.plot(x/np.pi,y)ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $pi$'))ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))plt.style.use("ggplot")plt.show()

给我

这看起来不太对

解决方案

这灵感来自

或者它可以以更复杂的方式使用:

tau = np.pi*2书房 = 60主要 = 倍数(den,tau,r'	au')次要 = 倍数(den*4,tau,r'	au')x = np.linspace(-tau/60, tau*8/60,500)plt.plot(x, np.exp(-x)*np.cos(60*x))plt.title(r'$	au$'的倍数)ax = plt.gca()ax.grid(真)ax.axhline(0, color='black', lw=2)ax.axvline(0, color='black', lw=2)ax.xaxis.set_major_locator(major.locator())ax.xaxis.set_minor_locator(minor.locator())ax.xaxis.set_major_formatter(major.formatter())plt.show()

的图

I'd like to make a plot in Python and have x range display ticks in multiples of pi.

Is there a good way to do this, not manually?

I'm thinking of using matplotlib, but other options are fine.

EDIT 3: EL_DON's solution worked for me like this:

import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi,1000)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")


plt.show()

giving:

EDIT 2 (solved in EDIT 3!): EL_DON's answer doesn't seem to work right for me:

import matplotlib.ticker as tck
import matplotlib.pyplot as plt
import numpy as np

f,ax=plt.subplots(figsize=(20,10))
x=np.linspace(-10*np.pi, 10*np.pi)
y=np.sin(x)

ax.plot(x/np.pi,y)

ax.xaxis.set_major_formatter(tck.FormatStrFormatter('%g $pi$'))
ax.xaxis.set_major_locator(tck.MultipleLocator(base=1.0))

plt.style.use("ggplot")

plt.show()

gives me

which really doesn't look right

解决方案

This is inspired by Python Data Science Handbook, although Sage attempts to do without explicit parameters.

EDIT: I've generalized this to allow you to supply as optional parameters the denominator, the value of the unit, and the LaTeX label for the unit. A class definition is included if you find that helpful.

import numpy as np
import matplotlib.pyplot as plt

def multiple_formatter(denominator=2, number=np.pi, latex='pi'):
    def gcd(a, b):
        while b:
            a, b = b, a%b
        return a
    def _multiple_formatter(x, pos):
        den = denominator
        num = np.int(np.rint(den*x/number))
        com = gcd(num,den)
        (num,den) = (int(num/com),int(den/com))
        if den==1:
            if num==0:
                return r'$0$'
            if num==1:
                return r'$%s$'%latex
            elif num==-1:
                return r'$-%s$'%latex
            else:
                return r'$%s%s$'%(num,latex)
        else:
            if num==1:
                return r'$frac{%s}{%s}$'%(latex,den)
            elif num==-1:
                return r'$frac{-%s}{%s}$'%(latex,den)
            else:
                return r'$frac{%s%s}{%s}$'%(num,latex,den)
    return _multiple_formatter
​
class Multiple:
    def __init__(self, denominator=2, number=np.pi, latex='pi'):
        self.denominator = denominator
        self.number = number
        self.latex = latex
​
    def locator(self):
        return plt.MultipleLocator(self.number / self.denominator)
​
    def formatter(self):
        return plt.FuncFormatter(multiple_formatter(self.denominator, self.number, self.latex))

This can be used very simply, without any parameters:

x = np.linspace(-np.pi, 3*np.pi,500)
plt.plot(x, np.cos(x))
plt.title(r'Multiples of $pi$')
ax = plt.gca()
ax.grid(True)
ax.set_aspect(1.0)
ax.axhline(0, color='black', lw=2)
ax.axvline(0, color='black', lw=2)
ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 12))
ax.xaxis.set_major_formatter(plt.FuncFormatter(multiple_formatter()))
plt.show()

Or it can be used in a more sophisticated way:

tau = np.pi*2
den = 60
major = Multiple(den, tau, r'	au')
minor = Multiple(den*4, tau, r'	au')
x = np.linspace(-tau/60, tau*8/60,500)
plt.plot(x, np.exp(-x)*np.cos(60*x))
plt.title(r'Multiples of $	au$')
ax = plt.gca()
ax.grid(True)
ax.axhline(0, color='black', lw=2)
ax.axvline(0, color='black', lw=2)
ax.xaxis.set_major_locator(major.locator())
ax.xaxis.set_minor_locator(minor.locator())
ax.xaxis.set_major_formatter(major.formatter())
plt.show()

这篇关于如何以 pi 的倍数设置轴刻度(Python)(matplotlib)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆