Python Forum
matplotlib x axis range goes over the set range
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
matplotlib x axis range goes over the set range
#1
I am just trying to do some simple plots, nothing fancy.

So I am trying y = x**2

I thought I set x in the range -4 to +4 with: x = np.arange(-4, 4, 0.2), but I get range 0 to 40 for x. (I suppose there are 40 0.2s in 8)

I would like the zero on the x-axis to coincide with the zero on the y-axis.

2 small problems:

1. How do I set x-axis zero and y-axis zero in the same place?
Ideally, x and y zero should be in the centre of the figure, so I see -4 to +4 on both axes.
2. How can I fix the range of x? (I would like a small interval in the range in order to give a smooth curve.)

def tp():
    fig = plt.figure(figsize=(6, 6))
    x = np.arange(-4, 4, 0.2)
    y = x**2    
    ax = fig.add_subplot(121)
    #ax2 = fig.add_subplot(122)
    #ax.fig(num='This is the title')

    # Move left y-axis and bottom x-axis to centre, passing through (0,0)
    ax.spines['left'].set_position('center')
    ax.spines['bottom'].set_position('zero')
    # Eliminate upper and right axes
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')

    # Show ticks in the left and lower axes only
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    ax.set_title('Full view')
    ax.plot(y, color='blue', label='y = x^2')
    
    plt.xlabel("X axis")
    plt.ylabel("Y = x^2")
    plt.legend()
    plt.show()
Reply


Messages In This Thread
matplotlib x axis range goes over the set range - by Pedroski55 - Nov-20-2021, 01:37 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  matplotlib x-axis text move bottom upward jacklee26 3 996 May-31-2023, 04:28 AM
Last Post: jacklee26
  [SOLVED] [loop] Exclude ranges in… range? Winfried 2 1,472 May-14-2023, 04:29 PM
Last Post: Winfried
Thumbs Down I hate "List index out of range" Melen 20 3,344 May-14-2023, 06:43 AM
Last Post: deanhystad
  How to check multiple columns value within range SamLiu 2 1,162 Mar-13-2023, 09:32 AM
Last Post: SamLiu
  Expand the range of a NumPy array? PythonNPC 0 756 Jan-31-2023, 02:41 AM
Last Post: PythonNPC
  Copying files if the name is in range tester_V 9 1,552 Nov-24-2022, 12:21 AM
Last Post: tester_V
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 6,395 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  Solving an equation by brute force within a range alexfrol86 3 2,812 Aug-09-2022, 09:44 AM
Last Post: Gribouillis
  IndexError: list index out of range dolac 4 1,923 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,357 Jun-26-2022, 09:50 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020