tkja
tkja

Reputation: 2030

matplotlib custom x-axes with custom number of ticks

After years of reading stackoverflow I reached a question that I cannot find an answer to, so I am starting here.

I am using python and matplotlib and want to plot with the xaxis starting from 1, nothing else being changed.

import matplotlib.pyplot as plt

y = range(1, 1000, 2)
plt.plot(y)
plt.show()

This plots but the x axis starts from 0. I tried to provide an x axis with

y = range(1, 1000, 2)
plt.plot(y)
plt.plot(range(1, len(y)+1), y)
plt.show()

but this does not change the x axis itself.

Another way I tried is to use plt.xticks and set the ticks myself.

y = range(1, 1000, 2)
plt.plot(y)
x = range(1, len(y)+1)
xstr = map(str, x)
plt.xticks(x, xstr)
plt.show()

But then I run into the problem of 500 xticks being drawn (or even more, if the y values contain a lot of data).

How can i simply plot the data with the xaxis displaying 1 instead of the 0 at the beginning, without the first element of the data to be left out or other data changes?

Upvotes: 0

Views: 2073

Answers (1)

nye17
nye17

Reputation: 13347

okay, xlim is not working, but why not just leave 1 and 1000 on the xticks?

plt.xticks([1, 1000])

Upvotes: 1

Related Questions