Monday, September 5, 2022

How to define xtics and ytics in Matplotlib?

The xtics and ytics are defined in matplotlib with matplotlib.pyplot.xtics and matplotlib.pyplot.ytics functions. The general form of these functions can be written as:
matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
matplotlib.pyplot.yticks(ticks=None, labels=None, **kwargs)
The arguments of both functions are ticks, labels and **kwargs. The ticks is an arry-like function argument and represent the list of xtick/ytick locations. Passing the empty list removes all xticks."labels" is an array-like function argument and represents the labels to place at given ticks locations. This argument can only be passed if ticks is passed as well. The minimum working example is plot the function \(y(x) = \cos(x)\). The enitre code is given below and the result of this code is shown in Figure 1.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,20.01,0.01)
y=[np.cos(x[i]) for i in range(len(x))]
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.xlabel("x")
plt.ylabel("y(x)")
plt.show()
The result is shown in the Figure 1.
Figure 1 - the graph with original x-ticks and y-ticks
Now instead of numbers on xticks we want to show numbers in a text form i.e.
['zero','two','four','six','eight','ten', 'twelwe',
'fortheen', 'sixtheen', 'eighteen', 'twenty']
. Instead of numbers on yticks we want to show numbers in a text form i.e.
['minus one', 'minus zero point five', 'zero', 'zero point five', 'one']
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0,20.01,0.01)
y = [np.cos(x[i]) for i in range(len(x))]
plt.figure(figsize=(12,8))
plt.plot(x,y)
plt.grid(True)
plt.xticks(ticks=[0,2,4,6,8,10,12,14,16,18,20],\
labels=['zero','two','four','six','eight','ten',
'twelwe', 'fortheen', 'sixtheen', 'eighteen', 'twenty'])
plt.yticks(ticks=[-1.0, -0.5, 0, 0.5, 1.0],\
labels=['minus one', 'minus zero point five',
'zero', 'zero point five', 'one'])
plt.show()
The result is shown in Figure 2.
Figure 2 - the graph with modified x-ticks and y-ticks

No comments:

Post a Comment