Home > database >  Matplotlib scatter plot x-axis value is messed up
Matplotlib scatter plot x-axis value is messed up

Time:09-24

The following demo code of my is producing a plot with the wrong x-axis value.

import matplotlib.pyplot as plt

x = [1.0, 1.0, 1.0, 1.0, 1.0, 0.9999390392587174, 1.0000609607412827, 1.0000609607412827]
y = [132, 136, 160, 192, 132, 136, 160, 192]

fig, ax = plt.subplots()
for i in range(len(x)):
    ax.scatter(x[i], y[i])

plt.savefig('demo.png')

This is the figure that it produces. In the picture, the x-axis seems to be scaled in some way that does not match the data in the code. Can anyone please explain what I did wrong? enter image description here

CodePudding user response:

It has scaled them correctly to the range of the x-values. The odd thing is how it's labelled. You can control this with

matplotlib.pyplot.xticks(ticks, labels, **kwargs)

Also see

x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
ax.xaxis.set_major_formatter(x_formatter)

which is the option to turn off the "offset" value (which is 1 in this case).

CodePudding user response:

Your x axis values are very close, so matplotlib automatically add an offset to x axis (notice 1 at the bottom right of the plot).
You can prevent it simply with:

ax.ticklabel_format(useOffset = False)

enter image description here

  • Related