用matplotlib画K线


参考:https://blog.csdn.net/u014281392/article/details/73611624

import tushare as ts
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.pylab import date2num
import mpl_finance as mpf
import datetime

wdyx = ts.get_k_data('002739', '2017-01-01')


# wdyx.info()
# print(wdyx.head())

def date_to_num(dates):
    num_time = []
    for date in dates:
        date_time = datetime.datetime.strptime(date, '%Y-%m-%d')
        num_date = date2num(date_time)
        num_time.append(num_date)
    return num_time


# Dataframe转换为二维数组
mat_wdyx = wdyx.values
num_time = date_to_num(mat_wdyx[:, 0])
mat_wdyx[:, 0] = num_time
# 接下来就可以绘制K线了
# 画布大小
fig, (ax0, ax1) = plt.subplots(2, sharex=True, figsize=(15, 8))
# 调整两个子画布大小(两种方法)
# ax0 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)
# ax1 = plt.subplot2grid((3, 1), (2, 0))
gs = GridSpec(3, 1)
# 调整上下间隔(两种方法)
# gs.update(hspace=0.05)

plt.subplots_adjust(hspace=0.05)
ax0 = plt.subplot(gs[0:2])
ax1 = plt.subplot(gs[2])

# 在第一个子画布上画K线,在第二个子画布上画量的柱线
mpf.candlestick_ochl(ax0, mat_wdyx, width=1, colorup='r', colordown='g', alpha=1.0)
ax0.set_title('wandayuanxian')
ax0.set_ylabel('Price')
ax0.grid(True)
plt.bar(mat_wdyx[:, 0]-0.4, mat_wdyx[:, 5], width=0.8)
ax1.xaxis_date()
ax1.set_ylabel('Volume')
plt.show()

运行如下图:

用matplotlib画K线_第1张图片


想要全部搞懂还是要下点功夫的,目前的问题,用subplots()函数创建画布和子图后figure1却不知道怎么改了,上下两个子图缩放不同步。

知识点:


plt.subplots()

figsize=(15,5)子图尺寸为15英寸x5英寸。

fig.subplots_adjust()

matplotlib.finance. candlestick_ochl ( axquoteswidth=0.2colorup='k'colordown='r'alpha=1.0 )

Plot the time, open, close, high, low as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown

Parameters:

ax : Axes

an Axes instance to plot to

quotes : sequence of (time, open, close, high, low, …) sequences

As long as the first 5 elements are these values, the record can be as long as you want (e.g., it may store volume).

time must be in float days format - see date2num

width : float

fraction of a day for the rectangle width

colorup : color

the color of the rectangle where close >= open

colordown : color

the color of the rectangle where close < open

alpha : float

the rectangle alpha level

Returns:

ret : tuple

returns (lines, patches) where lines is a list of lines added and patches is a list of the rectangle patches added



matplotlib.pyplot.subplots

matplotlib.pyplot. subplots ( nrows=1ncols=1sharex=Falsesharey=Falsesqueeze=Truesubplot_kw=Nonegridspec_kw=None**fig_kw ) [source]

Create a figure and a set of subplots

This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.

Parameters:
nrows, ncols  :  int, optional, default: 1

Number of rows/columns of the subplot grid.

sharex, sharey  :  bool or {‘none’, ‘all’, ‘row’, ‘col’}, default: False

Controls sharing of properties among x (sharex) or y (sharey) axes:

  • True or ‘all’: x- or y-axis will be shared among all subplots.
  • False or ‘none’: each subplot x- or y-axis will be independent.
  • ‘row’: each subplot row will share an x- or y-axis.
  • ‘col’: each subplot column will share an x- or y-axis.

When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are visible. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are visible.

squeeze  :  bool, optional, default: True
  • If True, extra dimensions are squeezed out from the returned Axes object:

    • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.
    • for Nx1 or 1xN subplots, the returned object is a 1D numpy object array of Axes objects are returned as numpy 1D arrays.
    • for NxM, subplots with N>1 and M>1 are returned as a 2D arrays.
  • If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.

subplot_kw  :  dict, optional

Dict with keywords passed to the add_subplot() call used to create each subplot.

gridspec_kw  :  dict, optional

Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.

**fig_kw :

All additional keyword arguments are passed to the figure() call.

Returns:
fig  :  matplotlib.figure.Figure object
ax  :  Axes object or array of Axes objects.

ax can be either a single matplotlib.axes.Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

See also

figuresubplot

Examples

First create some toy data:

>>> x = np.linspace(0, 2*np.pi, 400)
>>> y = np.sin(x**2)

Creates just a figure and only one subplot

>>> fig, ax = plt.subplots()
>>> ax.plot(x, y)
>>> ax.set_title('Simple plot')

Creates two subplots and unpacks the output array immediately

>>> f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
>>> ax1.plot(x, y)
>>> ax1.set_title('Sharing Y axis')
>>> ax2.scatter(x, y)

Creates four polar axes, and accesses them through the returned array

>>> fig, axes = plt.subplots(2, 2, subplot_kw=dict(polar=True))
>>> axes[0, 0].plot(x, y)
>>> axes[1, 1].scatter(x, y)

Share a X axis with each column of subplots

>>> plt.subplots(2, 2, sharex='col')

Share a Y axis with each row of subplots

>>> plt.subplots(2, 2, sharey='row')

Share both X and Y axes with all subplots

>>> plt.subplots(2, 2, sharex='all', sharey='all')

Note that this is the same as

>>> plt.subplots(2, 2, sharex=True, sharey=True)

matplotlib.pyplot.subplots_adjust

matplotlib.pyplot. subplots_adjust ( *args**kwargs ) [source]

Tune the subplot layout.

call signature:

subplots_adjust(left=None, bottom=None, right=None, top=None,
                wspace=None, hspace=None)

The parameter meanings (and suggested defaults) are:

left  = 0.125  # the left side of the subplots of the figure
right = 0.9    # the right side of the subplots of the figure
bottom = 0.1   # the bottom of the subplots of the figure
top = 0.9      # the top of the subplots of the figure
wspace = 0.2   # the amount of width reserved for space between subplots,
               # expressed as a fraction of the average axis width
hspace = 0.2   # the amount of height reserved for space between subplots,
               # expressed as a fraction of the average axis height

The actual defaults are controlled by the rc file

matplotlib.pyplot.figure

matplotlib.pyplot. figure ( num=Nonefigsize=Nonedpi=Nonefacecolor=Noneedgecolor=Noneframeon=TrueFigureClass=clear=False**kwargs ) [source]

Creates a new figure.

Parameters:
num  :  integer or string, optional, default: none

If not provided, a new figure will be created, and the figure number will be incremented. The figure objects holds this number in a number attribute. If num is provided, and a figure with this id already exists, make it active, and returns a reference to it. If this figure does not exists, create it and returns it. If num is a string, the window title will be set to this figure’s num.

figsize  :  tuple of integers, optional, default: None

width, height in inches. If not provided, defaults to rc figure.figsize.

dpi  :  integer, optional, default: None

resolution of the figure. If not provided, defaults to rc figure.dpi.

facecolor :

the background color. If not provided, defaults to rc figure.facecolor.

edgecolor :

the border color. If not provided, defaults to rc figure.edgecolor.

frameon  :  bool, optional, default: True

If False, suppress drawing the figure frame.

FigureClass  :  class derived from matplotlib.figure.Figure

Optionally use a custom Figure instance.

clear  :  bool, optional, default: False

If True and the figure already exists, then it is cleared.

Returns:
figure  :  Figure

The Figure instance returned will also be passed to new_figure_manager in the backends, which allows to hook custom Figure classes into the pylab interface. Additional kwargs will be passed to the figure init function.

Notes

If you are creating many figures, make sure you explicitly call “close” on the figures you are not using, because this will enable pylab to properly clean up the memory.

rcParams defines the default values, which can be modified in the matplotlibrc file




你可能感兴趣的:(用matplotlib画K线)