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?
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.
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.
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.
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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With