Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mark ticks in latex in matplotlib

In a plot in matplotlib I specially want to mark points on the x-axis as pi/2, pi, 3pi/2 and so on in latex. How can I do it?

like image 361
lovespeed Avatar asked Oct 16 '12 18:10

lovespeed


People also ask

How do I show a tick in MatPlotLib?

The two relevant classes are Locator s and Formatter s. Locators determine where the ticks are, and formatters control the formatting of tick labels. Minor ticks are off by default (using NullLocator and NullFormatter ). Minor ticks can be turned on without labels by setting the minor locator.

How do I create a custom tick in MatPlotLib?

Set the figure size and adjust the padding between and around the subplots. Create lists for height, bars and y_pos data points. Make a bar plot using bar() method. To customize X-axis ticks, we can use tick_params() method, with color=red, direction=outward, length=7, and width=2.

What are tick marks MatPlotLib?

Ticks are the markers denoting data points on axes. Matplotlib has so far - in all our previous examples - automatically taken over the task of spacing points on the axis. Matplotlib's default tick locators and formatters are designed to be generally sufficient in many common situations.


2 Answers

The plt.xticks command can be used to place LaTeX tick marks. See this doc page for more details.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

cos = np.cos
pi = np.pi

# This is not necessary if `text.usetex : True` is already set in `matplotlibrc`.    
mpl.rc('text', usetex = True)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
t = np.linspace(0.0, 2*pi, 100)
s = cos(t)
plt.plot(t, s)

plt.xticks([0, pi/2, pi, 3*pi/2, 2*pi],
           ['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
plt.show()

enter image description here

like image 81
unutbu Avatar answered Sep 30 '22 10:09

unutbu


Another possibility is to update the pyplot rcParams, although this might be rather a hack than a legitimate way.

import matplotlib.pyplot as plt
import numpy as np

cos = np.cos
pi  = np.pi

params = {'mathtext.default': 'regular' }  # Allows tex-style title & labels
plt.rcParams.update(params)

fig = plt.figure()
ax  = fig.add_subplot(1, 1, 1)
t   = np.linspace(0.0, 2*pi, 100)
s   = cos(t)
plt.plot(t, s)

ax.set_xticks([0, pi/2, pi, 3*pi/2, 2*pi])
ax.set_xticklabels(['$0$', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
plt.show()

Output

like image 24
Dan Doe Avatar answered Sep 30 '22 09:09

Dan Doe