1

I have list generated from a function I created. I am integrating a graph into my function output. As I am testing my graph the ticks on the x axis do not align with the correct points on the graph; they are offset by 1. The data at tick 0 should be tick 1 and so forth.

list = [0.38, 0.60, 0.65, 0.67, 0.71, 0.66, 0.65, 0.47, 0.71, 0.60]
plt.plot(list)
plt.show()

enter image description here

What I tried:

plt.xticks(np.arange(1, len(list)+1)

That graphs fine but still the same issue.

enter image description here

I just cannot seem to shift the xticks to line up with their corresponding points on the line graph. Any help is appreciated.

Matplotlib version 3.5.2 Python3 Numpy version 1.21.5 pandas 1.4.4

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

2 Answers2

2

Python uses zero-based indexing. plt.plot normally accepts arrays for x and y. If you only supply the latter, x is implicitly taken to be the index, which is zero based.

That means that your call to plot is equivalent to

lst = [0.38, 0.60, 0.65, 0.67, 0.71, 0.66, 0.65, 0.47, 0.71, 0.60]
plt.plot(np.arange(0, len(lst)), lst)

If you want to plot with one-based indices, state that explicitly:

plt.plot(np.arange(len(lst)) + 1, lst)

Oh, and don't call your variables list. You will regret it later when you try to call the built-in list and get a numpy.ndarray is not callable error or similar.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Thank you! This is exactly what I was trying to do! And I never call my lists just 'list', I was using it here just to be descriptive but I'll make sure I use something else even when posting here. – Wildo_Baggins311 Mar 09 '23 at 15:50
  • 1
    @Wildo_Baggins311. Don't forget to select the answer, even though your question was marked as a duplicate. – Mad Physicist Mar 09 '23 at 15:54
1

I think what you mean is that in the below figure (from your data), the first point starts at 0, while you expected it would start at 1?

enter image description here

This is expected behaviour, because Python uses zero-indexing, so the first (in colloquial sense) element is given index 0. If you want to change this, your proposed method with plt.xticks() does not work because it sets the location of the ticks, but does not offset them by 1. That can be done by also setting the ticklabels:

import matplotlib.pyplot as plt 
import numpy as np
ax = plt.subplot(111)

list_ex = [0.38, 0.60, 0.65, 0.67, 0.71, 0.66, 0.65, 0.47, 0.71, 0.60]
ax.plot(list_ex)
ax.set_xticks(np.arange(len(list_ex)))
ax.set_xticklabels(np.arange(len(list_ex)) + 1);

enter image description here

Thijs
  • 433
  • 8