Search code examples
pythonplotscatter

Python plot scatter data don't behave well on X axis


Not sure how to explain my problem, basically I'm trying to plot something with :

plt.scatter(fichi_i,fre_i,c=duree_i, s=50,cmap='hot')

Where "fichi_i" would be, for example :

[10, 21, 25, 28, 36, 41, 48]

I would like my X axis to start at 0 to 500 for instance. How to do that ? Without any indication the plot goes from 10 to 48.

Already tried the following that I've been using in other scripts:

plt.xlim(0,500)
    
ax.set_xticks(np.arange(0, 500, 50))

ax.set_xlim(0,500)    

plt.gca().set_xlim(left=0)

All gets the same result : the plot still start as 10.

And when I replace the "0" in previous lines with something let's say "10", the plot start at... 20 ! So it seems to do something but it's like the "0" in those commands is the first value of the "fichi_i" variable, not the actual 0 of the axis. And I managed to find a workaround by using instead of "0", "-10". So the x axis start at "0"... I didn't figure out how to change the max of the axis.

Now another problem is that on my plot the dots of the array have no "space" between them. Like there is the dot corresponding to "21" is right after the dot of the "10", there is not a blank corresponding to 10 values between them. My array here have "7" values, if I set the max lim of X axis to 7 I see them all. If I set it to 100 I have the 7 values and 93 blanks from 48 (which is the 7th value) to 100.

Basically how can I say "x axis goes from 0 to 100" and having the dots going to the proper positions, the 10 on the 10th value of x axis, ... It's working fine with a plot but with a scatter it's a nightmare Idk why the behavior is not the same.

The code I'm using to plot btw :

w, h = figaspect(1/3)
fig, ax = plt.subplots(1,figsize=(w,h))

plt.xlabel('test number')

plt.scatter(fichi_i,fre_i,c=duree_i, s=50,cmap='hot')
plt.colorbar(label='time(s)')
ylims = ax.get_ylim()
xlims = ax.get_xlim()  
plt.show()

Thanks. I hope I've been clear in my explanation was'nt sure how to explain.


Solution

  • Using plt.xlim(0, 500) works for me, I suspect it was incorrectly placed in the code. It has to be between:

    fig , ax = plt.subplots(1, figsize=(w,h))
    

    and

    plt.show()
    

    Full code:

    import matplotlib.pyplot as plt
    w, h = plt.figaspect(1/3)
    fig, ax = plt.subplots(1,figsize=(w,h))
    fichi_i = [10, 21, 25, 28, 36, 41, 48]
    fre_i = [10, 21, 25, 28, 36, 41, 48]
    duree_i = ['red' for _ in fre_i]
    plt.xlabel('test number')
    
    plt.scatter(fichi_i,fre_i,c=duree_i, s=50,cmap='hot')
    plt.colorbar(label='time(s)')
    ylims = ax.get_ylim()
    xlims = ax.get_xlim()  
    plt.xlim((10, 500))
    plt.show()
    

    enter image description here