sigma
sigma

Reputation: 247

Use custom tick marks on axes coordinates

I'm plotting some function in matplotlib. But I want to change the usual x and y coordinates. For example I plot y=sin(x) in [-pi, pi]. But the x-axis shows 1, 2, 3,... in this way whereas I want x: -pi, 0, pi,... Is it possible?

My Code

import matplotlib as mpl
mpl.rc('text', usetex = True)
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np

plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])

x = np.arange(-np.pi,np.pi,0.001)
y = np.sin(x)

plt.xlabel('$x$')
plt.ylabel('$y$')
plt.plot(x,y, label='$y=\sin x$')
plt.legend()
plt.show()

Output enter image description here

How to change the marks on the axes coordinates? Thank you.

Upvotes: 1

Views: 865

Answers (2)

Reblochon Masque
Reblochon Masque

Reputation: 36652

Yes, you can have custom tick marks on the axis, and set them equally spaced; for this you need to set the tick marks as a sequence, together with the values associated:

import matplotlib as mpl
mpl.rc('text', usetex = True)
mpl.rc('font', family = 'serif')
import matplotlib.pyplot as plt
import numpy as np


plt.gca().set_aspect('equal', adjustable='box')
plt.style.use(['ggplot','dark_background'])

x = np.arange(-np.pi,np.pi,0.001)
y = np.sin(x)

# the following two sequences contain the values and their assigned tick markers
xx = [-np.pi + idx*np.pi/4 for idx in range(10)]
xx_t = ['$-\\pi$', '$\\frac{-3\\pi}{4}$', '$\\frac{-\\pi}{2}$', '$\\frac{-\\pi}{4}$', '0', 
        '$\\frac{\\pi}{4}$', '$\\frac{\\pi}{2}$', '$\\frac{3\\pi}{4}$', '$\\pi$']
plt.xticks(xx, xx_t)   # <-- the mapping happens here

plt.xlabel('$x$')
plt.ylabel('$y$')
plt.plot(x,y, label='$y=\sin x$')
plt.legend()
plt.show()

enter image description here

Upvotes: 2

Sheldore
Sheldore

Reputation: 39042

Here you can display up to whichever range of pi you want to. Just add the following lines to your code after plt.plot

xlabs = [r'%d$\pi$'%i if i!=0 else 0 for i in range(-2, 3, 1)]
xpos = np.linspace(-2*np.pi, 2*np.pi, 5)
plt.xticks(xpos, xlabs)

Output enter image description here

Upvotes: 2

Related Questions