DHJ
DHJ

Reputation: 621

Xticks different interval

How do i set xticks to 'a different interval'

For instance:

plt.plot(1/(np.arange(0.1,3,0.1)))

returns:

enter image description here

If I would like the x axis to be on a scale from 0 to 3, how can i do that? I've tried

plt.xticks([0,1,2])

but that returns:

enter image description here

Upvotes: 4

Views: 1271

Answers (2)

Christoph Rackwitz
Christoph Rackwitz

Reputation: 15518

You want to learn about plt.xlim and adjacent functions. This causes the X axis to have limits (minimum, maximum) that you specify. Otherwise Matplotlib decides for you based on the values you try to plot.

y = 1 / np.arange(0.1,3,0.1)
plt.plot(y)
plt.xlim(0, 3) # minimum 0, maximum 3
plt.show()

figure 1

Your plot uses only Y values, so the X values are automatically chosen to be 1, 2, 3, ... to pair up with each Y value you provide.

If you desire to determine the X too, you can do that:

x = np.arange(0.1,3,0.1)
y = 1/x
plt.plot(x, y)
plt.xticks([0,1,2,3]) # ticks at those positions, if you don't like the automatic ones
plt.show()

figure 2

Upvotes: 1

Cardstdani
Cardstdani

Reputation: 5223

You can use numpy.arange() to get the desired range with a specific step:

import matplotlib.pyplot as plt
import numpy as np

y = 1/(np.arange(0.1,3,0.1))
plt.tight_layout()
plt.plot(y)
plt.xticks(np.arange(0, len(y), 6), [str(round(i, 2)) for i in np.arange(0, 3, (3*6)/len(y))])
plt.show()

enter image description here Also, you can see more examples of xticks() on the official matplotlib documentation.

Upvotes: 1

Related Questions