Ashwin Nanjappa
Ashwin Nanjappa

Reputation: 78568

How to specify the number of X ticks and their labels in Matplotlib?

I am plotting some data using the pyplot.plot() function of Matplotlib.

The X values for the data are integers, but these numbers do not mean anything. For example:

x_vals = [2, 34, 456, 999, 10000]

But, matplotlib thinks these are actual X values. It scales the X axis and shows ticks like this on the plot:

|
|
|
|
+---+----+----+----+----+
0   2000 4000 6000 8000 10000

What I want is for matplotlib to blindly plot using X axis like this:

|
|
|
|
+---+----+----+----+
2   34   456  999  10000

That is, I want the number of ticks to be equal to the number of X values I passed in. I also want the values to be blindly interpreted, possibly as strings.

How can this be done in Matplotlib?

Upvotes: 3

Views: 3059

Answers (1)

sodd
sodd

Reputation: 12933

One possible solution is to plot a range instead of the actual x-values along the x-axis, and then manually change the labels to the desired values.

In other words:

plt.plot(range(len(y_values)), y_values)
plt.gca().xaxis.set_ticklabels(x_values)

where, in this case, x_values = [2, 34, 10000].

Upvotes: 3

Related Questions