Search code examples
pythonmatplotlibplotaxis-labels

Shifting text on axis


I'am trying to shift the text I have added on my x-axis. Unfortunately I can't seem to manage to do so.

This is the code:

import numpy as np
import matplotlib.pyplot as plt

data = [[5., 25., 50., 20.],
    [4., 23., 51., 17.],
    [6., 22., 52., 19.]]
classes = ['Car', 'Home', 'House_num', 'River']

X = np.arange(4)
plt.bar(X + 0.00, data[0], color = 'b', width = 0.25)
plt.bar(X + 0.25, data[1], color = 'g', width = 0.25)
plt.bar(X + 0.50, data[2], color = 'r', width = 0.25)

plt.xticks(np.arange(5), classes)
plt.show()

This is the resulting graph:

Graph

I am trying to shift classes so that they are centred under the green bar. I have looked at the xticks documentation and found an argument locs which I believe is what I need to manually set the location (docs are here). This is my attempt (which does not work):

plt.xticks(np.arange(5), classes, locs=[1.2, 2.2, 3.2, 4.2])

locs values are just a test in the above code; they still need to be tuned for the right alignment. The alignment part isn't too important I am more interested in simply being able to manipulate the location of my labels. I'll take care of the fine tuning on my end.

Have a good day and thanks for taking your time to read this. Peace!


Solution

  • I suggest you to just replace this line:

    plt.xticks(np.arange(5), classes)
    

    with one of the following ones:

    plt.xticks(np.arange(0.25,5), classes)
    plt.xticks(X + 0.25, classes)