本文介绍了具有两个比例尺的Matplotlib轴共享原点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Matplotlib中,我需要两个重叠的两个具有不同Y轴比例的数据集.数据包含正值和负值.我希望两个轴共享一个原点,但是Matplotlib默认情况下不对齐两个比例.
I need two overlay two datasets with different Y-axis scales in Matplotlib. The data contains both positive and negative values. I want the two axes to share one origin, but Matplotlib does not align the two scales by default.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.bar(range(6), (2, -2, 1, 0, 0, 0))
ax2.plot(range(6), (0, 2, 8, -2, 0, 0))
plt.show()
我想可以用两个对齐两个刻度的.get_ylim()
和.set_ylim()
来执行一些计算.有更简单的解决方案吗?
I suppose it is possible to perform some computation with .get_ylim()
and .set_ylim()
two align the two scales. Is there an easier solution?
推荐答案
使用align_yaxis()函数:
use the align_yaxis() function:
import numpy as np
import matplotlib.pyplot as plt
def align_yaxis(ax1, v1, ax2, v2):
"""adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
_, y1 = ax1.transData.transform((0, v1))
_, y2 = ax2.transData.transform((0, v2))
inv = ax2.transData.inverted()
_, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
miny, maxy = ax2.get_ylim()
ax2.set_ylim(miny+dy, maxy+dy)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.bar(range(6), (2, -2, 1, 0, 0, 0))
ax2.plot(range(6), (0, 2, 8, -2, 0, 0))
align_yaxis(ax1, 0, ax2, 0)
plt.show()
这篇关于具有两个比例尺的Matplotlib轴共享原点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!