11

I'm trying to plot percent change data and would like to plot it such that the y axis is symmetric about 0. i.e. 0 is in the center of the axis.

import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame([1,2,3,4,3,6,7,8], columns=['Data'])
data['PctChange'] = data['Data'].pct_change()
data['PctChange'].plot()

percent change on default y axis

This is different from How to draw axis in the middle of the figure?. The goal here is not to move the x axis, but rather, change the limits of the y axis such that the zero is in the center. Specifically in a programmatic way that changes in relation to the data.

Gavin S
  • 642
  • 3
  • 8
  • 19
  • Does this answer your question? [How to draw axis in the middle of the figure?](https://stackoverflow.com/questions/31556446/how-to-draw-axis-in-the-middle-of-the-figure) – Bruno Mello Apr 05 '20 at 23:23
  • No. That's moving the x axis to align at a different position on the y axis. This is altering the y axis limits to be symmetric about zero. – Gavin S Apr 05 '20 at 23:52

2 Answers2

15

After plotting the data find the maximum absolute value between the min and max axis values. Then set the min and max limits of the axis to the negative and positive (respectively) of that value.

import matplotlib.pyplot as plt
import pandas as pd
data = pd.DataFrame([1,2,3,4,3,6,7,8], columns=['Data'])
data['PctChange'] = data['Data'].pct_change()
ax = data['PctChange'].plot()

yabs_max = abs(max(ax.get_ylim(), key=abs))
ax.set_ylim(ymin=-yabs_max, ymax=yabs_max)

percent change about symmetric y axis

Gavin S
  • 642
  • 3
  • 8
  • 19
1

One could implement Gavin's solution as a function:

import matplotlib.pyplot as plt
import numpy as np


def symmetrize_y_axis(axes):
    y_max = np.abs(axes.get_ylim()).max()
    axes.set_ylim(ymin=-y_max, ymax=y_max)


fig, ax = plt.subplots()
x = np.linspace(0, 20, 100)
y = np.exp(np.sin(x)) - 1.0
ax.plot(x, y)
symmetrize_y_axis(ax)

Plot with symmetrized y axis

angelo-peronio
  • 179
  • 1
  • 7