Zubo - 6 months ago 47
Python Question

# How to set axis ticks in multiples of pi (Python) (matplotlib)

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

f,ax=plt.subplots(1)
ax.xaxis.set_major_formatter(FormatStrFormatter('%g $\pi$'))