43

For example in the following code:

import numpy as np
import matplotlib.pyplot as plt

N = 10
x = [1,2,3,4,5,6,7,8,9,10]
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

I get the following plot

enter image description here

as you can see, in the x axis, only the even values appear. How to force matplotlib to show all values, that is 1 2 3 4 5 6 7 8 9 10?

cottontail
  • 10,268
  • 18
  • 50
  • 51
jsguy
  • 2,069
  • 1
  • 25
  • 36
  • 1
    By "all values" do you mean "all values in the input set" or "all integers in the input range"? For instance, if your passed x values `[1, 2.3, 5.2]`, would you want to see 1, 2.3 and 5.2 on the x axis, or 1, 2, 3, 4, 5, and 6? – BrenBarn Feb 13 '15 at 19:08
  • I would want to see, 1 2.3 and 5.2 – jsguy Feb 13 '15 at 19:09

2 Answers2

50

Use plt.xticks(x). See the documentation.

Note that using only the input values for ticks will usually be confusing to a viewer. It makes more sense to use evenly spaced ticks.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
1

Setting xticks using the values that are not evenly spaced makes a "bad" plot sometimes. For example, in the following case:

x = [1,2.9,3.1,4,5,6,7,8,9,10]
y = np.random.rand(10)

plt.scatter(x, y)
plt.xticks(x);

the x-tick labels are unreadable at some points.

res1

It's better if the tick labels are evenly spaced:

plt.scatter(x, y)
plt.xticks(range(min(x), max(x)+1));

res2

FYI, you can get the limits of an axis by calling plt.xlim() or plt.ylim() so that you can set more accurate tick labels. Also, with plt.xticks() (and plt.yticks()), you can set arbitrary tick labels. For example, instead of numbers, tick labels could be strings (e.g. a, b, c).

plt.scatter(x, y)
plt.xticks(range(min(x), max(x)+1));
ymin, ymax = plt.ylim()   # (0.19667230980587072, 1.0097016485006163)
plt.yticks(np.linspace(0, 1, 4), ['0', 'a', 'b', 'c']);
plt.ylim(ymin, ymax);

res3

The very same graph can be plotted by explicitly creating subplots and setting the properties of the Axes object as well.

fig, ax = plt.subplots(figsize=(5,2))
ax.scatter(x, y)
ax.set(xticks=np.arange(min(x), max(x)+1), yticks=np.linspace(0, 1, 4), yticklabels=['0', 'a', 'b', 'c'], ylim=ax.get_ylim());
cottontail
  • 10,268
  • 18
  • 50
  • 51