Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force zero (0) to the center of an axis in matplotlib

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.

like image 533
Gavin S Avatar asked Apr 05 '20 23:04

Gavin S


People also ask

How do I center origin in Matplotlib?

To put the origin at the center of the figure we use the spines module from the matplotlib module. Basically, spines are the lines connecting the axis tick marks and noting the boundaries of the data area.


1 Answers

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

like image 78
Gavin S Avatar answered Sep 22 '22 02:09

Gavin S