Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shift the x-axis over by one to start at 1 instead of 0?

How do I start plotting my values at position 1 on the x-axis rather than 0? All the solutions I have seen for this have been pretty complex, I think I must be overlooking a simple way to specify this.

import matplotlib.pyplot as plt

def plot_vals(vals, RANGE):
  plt.grid()
  plt.xticks(RANGE)
  plt.plot(vals, 'ro-')


RANGE = range(0, 11)

vals = [600.0, 222.3, 139.8, 114.0, 90.8, 80.8, 70.7, 62.8, 55.5, 47.5]
plot_vals(vals, RANGE)

yields this graph

enter image description here

All I want is x to run from 1 - 10 (instead 0 to 9) while keeping the all the values to be plotted.

like image 764
Levon Avatar asked Nov 07 '25 11:11

Levon


2 Answers

To ensure this, you can pass a range for the x argument of plt.plot that runs from 1 to length of the values:

plt.plot(range(1, len(vals) + 1), vals)

which gives this:

plot1

to see them in 1..10 fashion, we use plt.xticks with the same range:

plt.xticks(range(1, len(vals) + 1))

to get

enter image description here

overall:

x_range = range(1, len(vals) + 1)
plt.plot(x_range, vals)
plt.xticks(x_range)

(with the OOP style, last two lines' functions are ax.plot and ax.set_xticks)

like image 66
Mustafa Aydın Avatar answered Nov 10 '25 00:11

Mustafa Aydın


You can do plt.plot(RANGE, vals, 'ro-') where the first argument is for x-axis, the second argument for y-axis. But then both RANGE and vals will have to be the same length, so you will need RANGE = range(1, 11).

like image 39
mportes Avatar answered Nov 10 '25 00:11

mportes



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!