Python Matplotlib:具有相同刻度间距和不同比例的双y轴

时间:2017-07-14 09:26:59

标签: python matplotlib scale

我尝试在两个不同比例的y轴的公共图中显示两个不同的函数。仍然,网格线应该对齐。我想将漂亮的自动定位算法用于第一个y轴的刻度位置。我尝试过但尝试过但是我无法在第二个y轴上进行缩放。

# -*- coding: utf-8 -*-
"""
MWE for copying tick positions between y-axes
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np

def tick_function(x1):
    """ transform tick positions """
    x2 = x1 / 78.3
    return ["{0:.1f}".format(x) for x in x2]

x = np.arange(100)

plt.close('all')
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
ax1.plot(x, x*x)
ax1.set_xlabel(r"$x \rightarrow$")
ax1.set_ylabel(r"$x^2 \rightarrow$")
ax1_yticks = ax1.get_yticks() # get positions of the ax1 y-ticks in data coordinates
ax1_y_bounds = ax1.get_ybound() # get lower and upper limit of ax1 y-ticks

ax2 = ax1.twinx() # create 2nd y-axis
ax2.set_yticks(ax1_yticks) 
ax2.set_ybound(ax1.get_ybound())
ax2.set_yticklabels(tick_function(ax1_yticks))
ax2.autoscale(False)
ax2.plot(x,x)
ax2.set_ylabel(r'$x \rightarrow$')
ax1.grid(True)

fig1.set_tight_layout(True)
plt.show()

Twin y-axes, wrong scaling

ax2.set_yticklabel ...命令之前移动第二个绘图命令获得不同的缩放,但现在标签丢失(或者可能在绘图之外移动):

enter image description here

@importanceofbeingernest:谢谢,我错过了那篇文章 - 我已经更新并附上了解决我问题的代码。 "不完美"对于我的现实问题,缩放不是问题。但是你有任何想法,是否可以在放大时自动更新第二轴?

# -*- coding: utf-8 -*-
"""
MWE for copying tick positions between y-axes
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np

x = np.arange(100)

plt.close('all')
fig1 = plt.figure(1)
ax1 = fig1.add_subplot(111)
ax1.plot(x, x*x)
ax1.set_xlabel(r"$x \rightarrow$")
ax1.set_ylabel(r"$x^2 \rightarrow$")
ax1.grid(True)
ax1_yticks = ax1.get_yticks() # get positions of the ax1 y-ticks in data coordinates

ax2 = ax1.twinx() # create 2nd y-axis
ax2.plot(x,x)
ax2.set_ylabel(r'$x \rightarrow$')

l1 = ax1.get_ylim() # get y-limits for ax1 
l2 = ax2.get_ylim() # and ax2
# map yticks(ax1) ->  yticks(ax2) to cover the same range on both axes
f = lambda x : l2[0]+(x-l1[0])/(l1[1]-l1[0])*(l2[1]-l2[0])
ax2_yticks = f(ax1_yticks)
 # fix tick locations for ax2:
ax2.yaxis.set_major_locator(ticker.FixedLocator(ax2_yticks))

fig1.set_tight_layout(True)
plt.show()

enter image description here

0 个答案:

没有答案