python matplotlib创建2个子图共享轴属性

时间:2016-12-31 02:54:41

标签: python matplotlib

我正在使用以下代码创建一个包含2个子图的图:

fig, (ax1, ax2) = plt.subplots(2, sharex = True, figsize=(20, 6)) 

mpf.candlestick_ohlc(ax1,quotes, width=0.01)
ax1.xaxis_date()
ax1.xaxis.set_major_locator(mpl.dates.DayLocator(interval=1) )
ax1.xaxis.set_major_formatter(mpl.dates.DateFormatter('%a, %b %d \'%y'))
ax1.xaxis.set_minor_locator(mpl.dates.HourLocator(byhour=range(0,24,4)))
ax1.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%-H'))
ax1.grid(True)
ax1.grid(b=True, which='minor', color='0.7', linestyle='dotted')
ax2.tick_params(direction='out', pad=15)

majors=ax1.xaxis.get_majorticklocs()
chart_start, chart_end = (ax1.xaxis.get_view_interval()[0],ax1.xaxis.get_view_interval()[1])
for major in majors:
    ax1.axvspan(max (chart_start, major-(0.3333)),min(chart_end, major+(0.3333)),color="0.95", zorder=-1 )

plt.bar(quotes[:,0] , quotes[:, 5], width = 0.01)

plt.show()

这里得到的数字:

enter image description here

我希望底部的子图具有相同的网格,主要/次要刻度和axvspan作为上面的子图。我可以为ax1重写所有更改ax2的ax1 ...行,但我怀疑可能有一种方法可以为两个轴分配不同的元素(即网格,次要/主要刻度和axvspan)在1去?

1 个答案:

答案 0 :(得分:1)

确定找到了:

fig, (axes) = plt.subplots(2, sharex = True, figsize=(20, 6))

mpf.candlestick_ohlc(axes[0],quotes, width=0.01)
plt.bar(quotes[:,0] , quotes[:, 5], width = 0.01)

for i , axes[i] in enumerate(axes):
    axes[i].xaxis_date(tz="Europe/Berlin")
    axes[i].xaxis.set_major_locator(mpl.dates.DayLocator(interval=1) )
    axes[i].xaxis.set_major_formatter(mpl.dates.DateFormatter('%a, %b %d \'%y'))
    axes[i].xaxis.set_minor_locator(mpl.dates.HourLocator(byhour=range(0,24,4)))
    axes[i].xaxis.set_minor_formatter(mpl.dates.DateFormatter('%-H'))
    axes[i].tick_params(direction='out', pad=15)
    axes[i].grid(True)
    axes[i].grid(b=True, which='minor', color='0.7', linestyle='dotted')

    majors=axes[i].xaxis.get_majorticklocs()
    chart_start, chart_end = (axes[i].xaxis.get_view_interval()[0], axes[i].xaxis.get_view_interval()[1])
    for major in majors:
        axes[i].axvspan(max (chart_start, major-(0.3333)),min(chart_end, major+(0.3333)),color="0.95", zorder=-1 )

plt.show()