• 二十三、共享 X 轴

    二十三、共享 X 轴

    在这个 Matplotlib 数据可视化教程中,我们将讨论sharex选项,它允许我们在图表之间共享x轴。将sharex看做『复制 x』也许更好。

    在我们开始之前,首先我们要做些修剪并在另一个轴上设置最大刻度数,如下所示:

    1. ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=7, prune='upper'))

    以及

    1. ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='upper'))

    现在,让我们共享所有轴域之间的x轴。 为此,我们需要将其添加到轴域定义中:

    1. fig = plt.figure()
    2. ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
    3. plt.title(stock)
    4. plt.ylabel('H-L')
    5. ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1, sharex=ax1)
    6. plt.ylabel('Price')
    7. ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)
    8. plt.ylabel('MAvgs')

    上面,对于ax2ax3,我们添加一个新的参数,称为sharex,然后我们说,我们要与ax1共享x轴。

    使用这种方式,我们可以加载图表,然后我们可以放大到一个特定的点,结果将是这样:

    二十三、共享 X 轴 - 图1

    所以这意味着所有轴域沿着它们的x轴一起移动。 这很酷吧!

    接下来,让我们将[-start:]应用到所有数据,所以所有轴域都起始于相同地方。 我们最终的代码为:

    1. import matplotlib.pyplot as plt
    2. import matplotlib.dates as mdates
    3. import matplotlib.ticker as mticker
    4. from matplotlib.finance import candlestick_ohlc
    5. from matplotlib import style
    6. import numpy as np
    7. import urllib
    8. import datetime as dt
    9. style.use('fivethirtyeight')
    10. print(plt.style.available)
    11. print(plt.__file__)
    12. MA1 = 10
    13. MA2 = 30
    14. def moving_average(values, window):
    15. weights = np.repeat(1.0, window)/window
    16. smas = np.convolve(values, weights, 'valid')
    17. return smas
    18. def high_minus_low(highs, lows):
    19. return highs-lows
    20. def bytespdate2num(fmt, encoding='utf-8'):
    21. strconverter = mdates.strpdate2num(fmt)
    22. def bytesconverter(b):
    23. s = b.decode(encoding)
    24. return strconverter(s)
    25. return bytesconverter
    26. def graph_data(stock):
    27. fig = plt.figure()
    28. ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
    29. plt.title(stock)
    30. plt.ylabel('H-L')
    31. ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1, sharex=ax1)
    32. plt.ylabel('Price')
    33. ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)
    34. plt.ylabel('MAvgs')
    35. stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
    36. source_code = urllib.request.urlopen(stock_price_url).read().decode()
    37. stock_data = []
    38. split_source = source_code.split('\n')
    39. for line in split_source:
    40. split_line = line.split(',')
    41. if len(split_line) == 6:
    42. if 'values' not in line and 'labels' not in line:
    43. stock_data.append(line)
    44. date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
    45. delimiter=',',
    46. unpack=True,
    47. converters={0: bytespdate2num('%Y%m%d')})
    48. x = 0
    49. y = len(date)
    50. ohlc = []
    51. while x < y:
    52. append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
    53. ohlc.append(append_me)
    54. x+=1
    55. ma1 = moving_average(closep,MA1)
    56. ma2 = moving_average(closep,MA2)
    57. start = len(date[MA2-1:])
    58. h_l = list(map(high_minus_low, highp, lowp))
    59. ax1.plot_date(date[-start:],h_l[-start:],'-')
    60. ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='lower'))
    61. candlestick_ohlc(ax2, ohlc[-start:], width=0.4, colorup='#77d879', colordown='#db3f3f')
    62. ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=7, prune='upper'))
    63. ax2.grid(True)
    64. bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)
    65. ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
    66. xytext = (date[-1]+4, closep[-1]), bbox=bbox_props)
    67. ## # Annotation example with arrow
    68. ## ax2.annotate('Bad News!',(date[11],highp[11]),
    69. ## xytext=(0.8, 0.9), textcoords='axes fraction',
    70. ## arrowprops = dict(facecolor='grey',color='grey'))
    71. ##
    72. ##
    73. ## # Font dict example
    74. ## font_dict = {'family':'serif',
    75. ## 'color':'darkred',
    76. ## 'size':15}
    77. ## # Hard coded text
    78. ## ax2.text(date[10], closep[1],'Text Example', fontdict=font_dict)
    79. ax3.plot(date[-start:], ma1[-start:], linewidth=1)
    80. ax3.plot(date[-start:], ma2[-start:], linewidth=1)
    81. ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
    82. where=(ma1[-start:] < ma2[-start:]),
    83. facecolor='r', edgecolor='r', alpha=0.5)
    84. ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
    85. where=(ma1[-start:] > ma2[-start:]),
    86. facecolor='g', edgecolor='g', alpha=0.5)
    87. ax3.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    88. ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
    89. ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='upper'))
    90. for label in ax3.xaxis.get_ticklabels():
    91. label.set_rotation(45)
    92. plt.setp(ax1.get_xticklabels(), visible=False)
    93. plt.setp(ax2.get_xticklabels(), visible=False)
    94. plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
    95. plt.show()
    96. graph_data('EBAY')

    下面我们会讨论如何创建多个y轴。