如何在matplotlib中强制零(0)到轴的中心 [英] How to force zero (0) to the center of an axis in matplotlib

查看:89
本文介绍了如何在matplotlib中强制零(0)到轴的中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绘制百分比变化数据,并希望绘制它以使 y 轴关于 0 对称.即 0 在轴的中心.

 将matplotlib.pyplot导入为plt将熊猫作为pd导入数据= pd.DataFrame([1,2,3,4,3,6,7,8],列= ['Data'])数据['PctChange'] = 数据['数据'].pct_change()数据['PctChange'].plot()

这与

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()

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.

解决方案

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)

这篇关于如何在matplotlib中强制零(0)到轴的中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆