Given the following code:
import matplotlib.pyplot as plt
import numpy as np
x = [1.0, 1.1, 2.0, 5.7]
y = np.arange(len(x))
fsize=(2,2)
fig, ax = plt.subplots(1,1,figsize=fsize)
ax.set_yticklabels(['a','b','c','d'])
ax.barh(y,x,align='center',color='grey')
plt.show()
Why are the labels not showing as expected ('a' does not show up and everything is shifted down by 1 place)?
To create a list of ticks, we will use numpy. arange(start, stop, step) with start as the starting value for the ticks, stop as the non-inclusive ending value and step as the integer space between ticks. Below example illustrate the matplotlib. pyplot.
MatPlotLib with Python Create x and y data points using numpy. Plot x and y data points using plot() method. Initialize a variable freq_x to adjust the frequency of the xticks. Use xticks() method to set the xticks.
To change the range of X and Y axes, we can use xlim() and ylim() methods.
Rotate X-Axis Tick Labels in Matplotlib There are two ways to go about it - change it on the Figure-level using plt. xticks() or change it on an Axes-level by using tick. set_rotation() individually, or even by using ax. set_xticklabels() and ax.
The locator is generating an extra tick on each side (which are not being shown because they is outside the plotted data). Try the following:
>>> ax.get_yticks()
array([-1., 0., 1., 2., 3., 4.])
You have a couple of options. You can either hard-code your tick labels to include the extra ticks (which I think is a bad idea):
ax.set_yticklabels(list(' abcd')) # You don't really need 'e'
Or, you can set the ticks to where you want them to be along with the labels:
ax.set_yticks(y)
ax.set_yticklabels(list('abcd'))
A more formal solution to the tick problem would be to set a Locator
object on the y-axis. The tick label problem is formally solved by setting the Formatter
for the y-axis. That is essentially what is happening under the hood when you call set_yticks
and set_yticklabels
anyway, but this way you have full control:
from matplotlib.ticker import FixedLocator, FixedFormatter
...
ax.yaxis.set_major_locator(FixedLocator(y))
ax.yaxis.set_major_formatter(FixedFormatter(list('abcd')))
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