默认情况下,艺术家首先在ax 上绘制,然后是
双轴上的艺术家ax2 在顶部。因此,由于在您的代码中,线图是在 ax 上绘制的,而条形图是在 ax2 上绘制的,因此条形图位于(并遮住)线的顶部。
(我以为我可以通过指定 zorder 来改变这一点,但那次尝试并没有
工作......)
所以解决问题的一种方法是使用ax 绘制条形图,使用ax2 绘制线条。这会将线放在条形图的顶部。默认情况下,它还会将ax(条形图)的ytick 标签放在左侧,将ax2(线条)的ytick 标签放在右侧。但是,您可以使用
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
交换左右 ytick 标签的位置。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
np.random.seed(2015)
N = 16
df = pd.DataFrame({'Opportunities': np.random.randint(0, 30, size=N),
'Percentage': np.random.randint(0, 100, size=N)},
index=pd.date_range('2015-3-15', periods=N, freq='B').date)
fig, ax = plt.subplots()
df[['Opportunities']].plot(kind='bar', stacked=False, title='get_title',
color='grey', ax=ax, grid=False)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(), df[['Percentage']].values, linestyle='-', marker='o',
color='k', linewidth=1.0, label='percentage')
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='best')
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
fig.autofmt_xdate()
plt.show()
产量
或者,可以设置轴的zorder,以便在ax2 上方绘制ax。 Paul Ivanov shows how:
ax.set_zorder(ax2.get_zorder()+1) # put ax in front of ax2
ax.patch.set_visible(False) # hide the 'canvas'
ax2.patch.set_visible(True) # show the 'canvas'
因此,
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
np.random.seed(2015)
N = 16
df = pd.DataFrame({'Opportunities': np.random.randint(0, 30, size=N),
'Percentage': np.random.randint(0, 100, size=N)},
index=pd.date_range('2015-3-15', periods=N, freq='B').date)
fig, ax = plt.subplots()
ax2 = ax.twinx()
df[['Opportunities']].plot(kind='bar', stacked=False, title='get_title',
color='grey', ax=ax2, grid=False)
ax.plot(ax.get_xticks(), df[['Percentage']].values, linestyle='-', marker='o',
color='k', linewidth=1.0, label='percentage')
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='best')
ax.set_zorder(ax2.get_zorder()+1) # put ax in front of ax2
ax.patch.set_visible(False) # hide the 'canvas'
ax2.patch.set_visible(True) # show the 'canvas'
fig.autofmt_xdate()
plt.show()
无需交换ax 和ax2 所扮演的角色即可产生相同的结果。