为了让我们的日K图更加易于比较,我们可以为它添加网格,用到的函数如下:
def grid(self, visible=None, which='major', **kwargs):
"""
Configure the grid lines.
Parameters
----------
visible : bool or None
Whether to show the grid lines. If any *kwargs* are supplied, it
is assumed you want the grid on and *visible* will be set to True.
If *visible* is *None* and there are no *kwargs*, this toggles the
visibility of the lines.
which : {'major', 'minor', 'both'}
The grid lines to apply the changes on.
**kwargs : `.Line2D` properties
Define the line properties of the grid, e.g.::
grid(color='r', linestyle='-', linewidth=2)
"""
if kwargs:
if visible is None:
visible = True
elif not visible: # something false-like but not None
_api.warn_external('First parameter to grid() is false, '
'but line properties are supplied. The '
'grid will be enabled.')
visible = True
which = which.lower()
_api.check_in_list(['major', 'minor', 'both'], which=which)
gridkw = {'grid_' + item[0]: item[1] for item in kwargs.items()}
if which in ['minor', 'both']:
gridkw['gridOn'] = (not self._minor_tick_kw['gridOn']
if visible is None else visible)
self.set_tick_params(which='minor', **gridkw)
if which in ['major', 'both']:
gridkw['gridOn'] = (not self._major_tick_kw['gridOn']
if visible is None else visible)
self.set_tick_params(which='major', **gridkw)
self.stale = True
如果我们想要以x轴为标准添加网格,则代码示例如下:
ax.grid(axis='x', linestyle='-.')
修改后的完整代码如下:(主要是增加了26、27行两行代码)
# 仅制作单股票的日K图,添加网格
import pandas
import matplotlib.pyplot as plt
import mpl_finance as mpf
dir_name = 'D:\gupiao\'
def paint_dayk(code):
# 1、获取数据
stock_data = pandas.read_csv(dir_name + code + '.txt') # 读取数据
begin = len(stock_data) - 120 # 取最近120天的数据
if begin < 0: # 如果上市未满120天,则从上市当天开始显示
begin = 0
# 2、画日K图
fig = plt.figure( # 添加fig对象
figsize=(54, 28), # 设置fig大小,长和宽,单位为英寸
dpi=120) # 每英寸的像素点数
gs = fig.add_gridspec(1, 1) # 在fig中添加一个一行一列的网格
ax = fig.add_subplot(gs[0, 0]) # 在fig中添加网格的第一块,并返回一套坐标轴
mpf.candlestick2_ochl( # 调用candlestick2_ochl画日K图
ax, # 在这套坐标轴内画日K图
stock_data.open[begin:], stock_data.close[begin:], # 开盘价和收盘价
stock_data.high[begin:], stock_data.low[begin:], # 最高价和最低价
width=0.8, colorup='red', colordown='green') # 收盘价大于开盘价则红柱,收盘价小于开盘价则绿柱
ax.grid(axis='x', linestyle='-.')
ax.grid(axis='y', linestyle='-.')
# 3、输出日K图
plt.savefig(dir_name + code + '.jpg') # 保存图片
def main():
code = '000001'
paint_dayk(code)
if __name__ == '__main__':
main()
运行后生成的图片如下:



