12

I am creating a plot with matplotlib

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)

Can I flip the plot, making the y-axis inverted and all positive values negative and vice versa?

I know I can multiply by -1 and use invert_yaxis but I wonder if there is a function for flipping it without changing the values.

ali_m
  • 71,714
  • 23
  • 223
  • 298
Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • 2
    relevant? http://stackoverflow.com/questions/1760614/turning-y-axis-upside-down-in-matlab – Aziz Apr 27 '15 at 22:16
  • It sounds like `plt.plot(x, -y)` would do exactly what you're looking for. What don't you like about *"changing the values"*? – ali_m Apr 28 '15 at 00:31
  • 1
    Somehow I find your question hard to understand. On one hand you want to change the values (*making the y-axis inverted and all positive values negative and vice versa?*) and on the other hand you explicitly don't want to change the values (*I wonder if there is a function for flipping it without changing the values*). Could you clarify what the question is? – hitzg Apr 28 '15 at 08:35

2 Answers2

18

Try the following function:

plt.gca().invert_yaxis()
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
2

Inverting y limits from (-1.1,1.1) to (1.1,-1.1) with plt.ylim will do the trick...

x = np.linspace(0, 2*np.pi, 63)
y = np.sin(x)
plt.plot(x, y)  
plt.ylim(1.1,-1.1)

Note that (1.1,-1.1) are just 10% above and below y.max() and y.min() values, preventing the y line from touching the graph box. Note also that x =np.arange(0, 5, .1) does not cover a complete sinusoidal period, 2 pi radians... x = np.linspace(0, 2*np.pi, 63) solves this little issue with same len(x) provided by np.arange(0, 5, .1).

john-hen
  • 4,410
  • 2
  • 23
  • 40
ePuntel
  • 91
  • 3