Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib scatter plot x-axis value is messed up

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

like image 440
Song Tùng Avatar asked Jun 26 '26 18:06

Song Tùng


2 Answers

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).

like image 170
Sanjay Manohar Avatar answered Jun 28 '26 08:06

Sanjay Manohar


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

like image 20
Zephyr Avatar answered Jun 28 '26 08:06

Zephyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!