二十、将子图应用于我们的图表

优质
小牛编辑
137浏览
2023-12-01

在这个 Matplotlib 教程中,我们将处理我们以前教程的代码,并实现上一个教程中的子图配置。 我们的起始代码是这样:

  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. def bytespdate2num(fmt, encoding='utf-8'):
  13. strconverter = mdates.strpdate2num(fmt)
  14. def bytesconverter(b):
  15. s = b.decode(encoding)
  16. return strconverter(s)
  17. return bytesconverter
  18. def graph_data(stock):
  19. fig = plt.figure()
  20. ax1 = plt.subplot2grid((1,1), (0,0))
  21. stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1m/csv'
  22. source_code = urllib.request.urlopen(stock_price_url).read().decode()
  23. stock_data = []
  24. split_source = source_code.split('\n')
  25. for line in split_source:
  26. split_line = line.split(',')
  27. if len(split_line) == 6:
  28. if 'values' not in line and 'labels' not in line:
  29. stock_data.append(line)
  30. date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
  31. delimiter=',',
  32. unpack=True,
  33. converters={0: bytespdate2num('%Y%m%d')})
  34. x = 0
  35. y = len(date)
  36. ohlc = []
  37. while x < y:
  38. append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
  39. ohlc.append(append_me)
  40. x+=1
  41. candlestick_ohlc(ax1, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
  42. for label in ax1.xaxis.get_ticklabels():
  43. label.set_rotation(45)
  44. ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
  45. ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
  46. ax1.grid(True)
  47. bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)
  48. ax1.annotate(str(closep[-1]), (date[-1], closep[-1]),
  49. xytext = (date[-1]+4, closep[-1]), bbox=bbox_props)
  50. ## # Annotation example with arrow
  51. ## ax1.annotate('Bad News!',(date[11],highp[11]),
  52. ## xytext=(0.8, 0.9), textcoords='axes fraction',
  53. ## arrowprops = dict(facecolor='grey',color='grey'))
  54. ##
  55. ##
  56. ## # Font dict example
  57. ## font_dict = {'family':'serif',
  58. ## 'color':'darkred',
  59. ## 'size':15}
  60. ## # Hard coded text
  61. ## ax1.text(date[10], closep[1],'Text Example', fontdict=font_dict)
  62. plt.xlabel('Date')
  63. plt.ylabel('Price')
  64. plt.title(stock)
  65. #plt.legend()
  66. plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
  67. plt.show()
  68. graph_data('EBAY')

一个主要的改动是修改轴域的定义:

  1. ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
  2. plt.title(stock)
  3. ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1)
  4. plt.xlabel('Date')
  5. plt.ylabel('Price')
  6. ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1)

现在,ax2是我们实际上在绘制的股票价格数据。 顶部和底部图表将作为指标信息。

在我们绘制数据的代码中,我们需要将ax1更改为ax2

  1. candlestick_ohlc(ax2, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
  2. for label in ax2.xaxis.get_ticklabels():
  3. label.set_rotation(45)
  4. ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
  5. ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
  6. ax2.grid(True)
  7. bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)
  8. ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
  9. xytext = (date[-1]+4, closep[-1]), bbox=bbox_props)

更改之后,代码为:

  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. def bytespdate2num(fmt, encoding='utf-8'):
  13. strconverter = mdates.strpdate2num(fmt)
  14. def bytesconverter(b):
  15. s = b.decode(encoding)
  16. return strconverter(s)
  17. return bytesconverter
  18. def graph_data(stock):
  19. fig = plt.figure()
  20. ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
  21. plt.title(stock)
  22. ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1)
  23. plt.xlabel('Date')
  24. plt.ylabel('Price')
  25. ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1)
  26. stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1m/csv'
  27. source_code = urllib.request.urlopen(stock_price_url).read().decode()
  28. stock_data = []
  29. split_source = source_code.split('\n')
  30. for line in split_source:
  31. split_line = line.split(',')
  32. if len(split_line) == 6:
  33. if 'values' not in line and 'labels' not in line:
  34. stock_data.append(line)
  35. date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
  36. delimiter=',',
  37. unpack=True,
  38. converters={0: bytespdate2num('%Y%m%d')})
  39. x = 0
  40. y = len(date)
  41. ohlc = []
  42. while x < y:
  43. append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
  44. ohlc.append(append_me)
  45. x+=1
  46. candlestick_ohlc(ax2, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
  47. for label in ax2.xaxis.get_ticklabels():
  48. label.set_rotation(45)
  49. ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
  50. ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
  51. ax2.grid(True)
  52. bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)
  53. ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
  54. xytext = (date[-1]+4, closep[-1]), bbox=bbox_props)
  55. ## # Annotation example with arrow
  56. ## ax1.annotate('Bad News!',(date[11],highp[11]),
  57. ## xytext=(0.8, 0.9), textcoords='axes fraction',
  58. ## arrowprops = dict(facecolor='grey',color='grey'))
  59. ##
  60. ##
  61. ## # Font dict example
  62. ## font_dict = {'family':'serif',
  63. ## 'color':'darkred',
  64. ## 'size':15}
  65. ## # Hard coded text
  66. ## ax1.text(date[10], closep[1],'Text Example', fontdict=font_dict)
  67. #
  68. #plt.legend()
  69. plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
  70. plt.show()
  71. graph_data('EBAY')

结果为:

二十、将子图应用于我们的图表 - 图1