Search code examples
pythonnumpymatplotlibseaborn

How to start the x-axis ticks at 1 (instead of 0) when plotting a Numpy array using Seaborn lineplot


Let's assume the following array of length 15:

import numpy as np

arr = np.array([0.17, 0.15, 0.13, 0.12, 0.07, 0.06, 0.05, 0.05, 0.03, 0.03, 0.03, 0.03, 0.03, 0.03, 0.02])
arr

array([0.17, 0.15, 0.13, 0.12, 0.07, 0.06, 0.05, 0.05, 0.03, 0.03, 0.03,
       0.03, 0.03, 0.03, 0.02])

I take the cumulative sum of this array and assign it to cum_arr:

cum_arr = np.cumsum(arr)
cum_arr

array([0.17, 0.32, 0.45, 0.57, 0.64, 0.7 , 0.75, 0.8 , 0.83, 0.86, 0.89,
       0.92, 0.95, 0.98, 1.  ])

Now, I'd like to simply plot this array using a Seaborn's lineplot.

My attempt:

import matplotlib.pyplot as plt
import seaborn as sns

x_range = [x for x in range(1, len(cum_arr) +1)]

ax = sns.lineplot(data=cum_arr)
ax.set_xlim(1, 15)
ax.set_ylim(0, 1.1)
ax.set_xticks(x_range)

plt.grid()
plt.show()

Which gives:

enter image description here

Notice how the y coordinate associated with 1 on the x-axis is 0.32, which corresponds to the second element in cum_arr.

The desired plot would look something like this:

enter image description here

How would I start plotting at the first element in cum_arr? (or alternatively adjust the xticks to take this into account)

Thanks!


Solution

  • If you only pass a 1-D data series to the plotting function then all it can do is plot the data against the index (0,1,2...) which is what is happening. So the problem is that you are not defining the values that cum_arr are to be plotted against. Just defining x_range as you have done has no effect if it is not passed to the plotting function. To specify the x and y you should use:

    ax = sns.lineplot(y= cum_arr, x= x_range)
    

    and you will get the expected plot.