How to display all label values in matplotlib

Question:

I have two lists, when I plot with the following code, the x axis only shows up to 12 (max is 15). May I know how can I show all of the values in x list to the x axis? Thanks in advance.

x = [4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3]
y = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(np.arange(len(x)), y, 'o')
ax1.set_xticklabels(x)
plt.show()

If I set minor=True in the set_xticklabels function, it shows me all x=2,4,6,8,..,16… but I want ALL values.

P.S. My x axis is not sorted, should display as it shows.

Asked By: Kevin

||

Answers:

The issue here is that the number of ticks -set automatically – isn’t the same as the number of points in your plot.

To resolve this, set the number of ticks:

ax1.set_xticks(np.arange(len(x)))

Before the ax1.set_xticklabels(x) call.

Answered By: farenorth

or better

ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

from other answers in SO

from matplotlib import ticker
import numpy as np

labels = [
    "tench",
    "English springer",
    "cassette player",
    "chain saw",
    "church",
    "French horn",
    "garbage truck",
    "gas pump",
    "golf ball",
    "parachute",
]
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title('Confusion Matrix', fontsize=18)
data = np.random.random((10,10))
ax.matshow(data, cmap=plt.cm.Blues, alpha=0.7)
ax.set_xticklabels([''] + labels,rotation=90)
ax.set_yticklabels([''] + labels)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
for i in range(data.shape[0]):
    for j in range(data.shape[1]):
        ax.text(x=j, y=i,s=int(data[i, j]), va='center', ha='center', size='xx-small')


plt.xlabel('Predicted')
plt.ylabel('True')
plt.show()

enter image description here

Answered By: Alex Punnen