双y轴,带有匹配的网格线

时间:2018-01-04 08:00:39

标签: python matplotlib

我想生成一个matplotlib折线图,其中两个变量显示在两个具有匹配网格线的y轴上。除了匹配的网格线部分之外,这一切都非常简单。以下是一些可重现的片段,包括最佳尝试。最后可以找到一个完整的片段。

带有初始情节的可重复数据框

根据Adding a y-axis label to secondary y-axis in matplotlib的建议,我能够制作出来:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


# Dataframe with some random numbers
np.random.seed(123)
rows = 4
df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB'))
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df['B'] = df['A'] * np.random.uniform(0.6,1.4, size = 4)

# Plot 1
fig, ax = plt.subplots()
t = df.index
ax.plot(t, df['A'])
ax2 = ax.twinx()
ax2.plot(t, df['B'], color='red')
ax2.yaxis.grid(which="major", color='green', linestyle='--')

ax.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()

Plot 1

enter image description here

如您所见,matplotlib为两个变量选择合理的间隔,但y轴的网格线不能很好地匹配。根据{{​​3}}的建议,我能够对齐它们,但这自然会遗漏一些值:

Plot 2

# Plot 2
fig, ax = plt.subplots()
t = df.index
ax.plot(t, df['A'])
ax2 = ax.twinx()
ax2.plot(t, df['B'], color='red')
#--
ax2.set_ylim(ax.get_ylim())

ax2.yaxis.grid(which="major", color='green', linestyle='--')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()

Align secondary y-axis ticks with stripplot on primary x-axis

我的下一次尝试是使用ax2int = ax2.get_ylim()[1] - ax2.get_ylim()[0]检索辅助y轴的间隔,并将其除以主轴上的网格线数,以使它们匹配。然后使用np.arange(start, stop, steps)关注enter image description here中的建议。但是我无法完全弄清楚如何完美匹配间隔,如下所示:

fig, ax = plt.subplots()
t = df.index
ax.plot(t, df['A'])
ax2 = ax.twinx()
ax2.plot(t, df['B'], color='red')

# The math
firstStep = ax.get_yticks()[1] - ax.get_yticks()[0]
ax2int = ax2.get_ylim()[1] - ax2.get_ylim()[0]
axSteps = len(ax.get_yticks()) 
newIntervals = ax2int / axSteps

# My best attempt
myticks = np.arange(min(df['B']), max(df['B']), newIntervals)
ax2.set(yticks=myticks)
ax2.yaxis.grid(which="major", color='green', linestyle='--')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')

plt.show()

剧情3

Changing the “tick frequency” on x or y axis in matplotlib

任何建议都会很棒!也许在matplotlib中已经有一些内置的功能来做这些事情了吗?谢谢!

这里有一个简单的复制粘贴的全部内容:

# Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


# Dataframe with some random numbers
np.random.seed(123)
rows = 4
df = pd.DataFrame(np.random.randint(90,110,size=(rows, 2)), columns=list('AB'))
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df['B'] = df['A'] * np.random.uniform(0.6,1.4, size = 4)

# Plot 1
fig, ax = plt.subplots()
t = df.index
ax.plot(t, df['A'])
ax2 = ax.twinx()
ax2.plot(t, df['B'], color='red')
ax2.yaxis.grid(which="major", color='green', linestyle='--')

ax.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()
#%%

# Plot 2
fig, ax = plt.subplots()
t = df.index
ax.plot(t, df['A'])
ax2 = ax.twinx()
ax2.plot(t, df['B'], color='red')
#--
ax2.set_ylim(ax.get_ylim())

ax2.yaxis.grid(which="major", color='green', linestyle='--')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()
#%%

# Plot 3 
fig, ax = plt.subplots()
t = df.index
ax.plot(t, df['A'])
ax2 = ax.twinx()
ax2.plot(t, df['B'], color='red')

# The math
firstStep = ax.get_yticks()[1] - ax.get_yticks()[0]
ax2int = ax2.get_ylim()[1] - ax2.get_ylim()[0]
axSteps = len(ax.get_yticks()) 
newIntervals = ax2int / axSteps

# My best attempt
myticks = np.arange(min(df['B']), max(df['B']), newIntervals)
ax2.set(yticks=myticks)
ax2.yaxis.grid(which="major", color='green', linestyle='--')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')

plt.show()

1 个答案:

答案 0 :(得分:2)

手动对齐第二轴的yticks非常棘手,因为(a)并非显示所有yticks(例如print(ax.get_yticks())并与您的情节进行比较)和(b)因为set_yticks()也会影响ylims。使用以下内容替换您的部分#The math#My best attempt

# The math
ylim1 = ax.get_ylim()
len1 = ylim1[1]-ylim1[0]
yticks1 = ax.get_yticks()
rel_dist = [(y-ylim1[0])/len1 for y in yticks1]
ylim2 = ax2.get_ylim()
len2 = ylim2[1]-ylim2[0]
yticks2 = [ry*len2+ylim2[0] for ry in rel_dist]

#My best attempt
ax2.set_yticks(yticks2)
ax2.set_ylim(ylim2)  #<-- this line is needed to re-adjust the limits to the original values
ax.yaxis.grid(which="major", color='black', linestyle='-')
ax2.yaxis.grid(which="major", color='green', linestyle='--')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')

,结果图如下所示:

enter image description here

希望这有帮助。