使用Python pandas+matplotlib+mpl_finance画K线图

使用Python pandas+matplotlib+mpl_finance画K线图_第1张图片

 Python数据分析笔记之使用Python pandas+matplotlib+mpl_finance画K线图

1、首先导入库

# coding=utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mpl_finance as mpf
import warnings

2、创建数据(数据是自己造的,仅供练习,应用时把自己的数据做个预处理就行了,保持格式一致就行了)

d = {'最高':[132,135,136,137,139,136,132,130,130,134,135,132,132,137,138,136,136,140,122,138,135,142,141,144,144,139],
     '最低':[120,120,110,119,120,119,110,88,120,115,100,110,110,115,121,124,81,124,122,118,108,100,110,93,100,119],
     '开始':[127,126,124,133,126,120,119,125,123,122,127,123,127,128,127,128,81,132,127,129,125,129,132,93,133,119],
     '结束':[126,130,132,126,130,125,125,91,126,126,116,126,126,128,127,126,131,129,122,125,108,131,135,134,119,128]
    }
df = pd.DataFrame(d)

3、查看数据(前五行)

df.head()

 输出结果:

 使用Python pandas+matplotlib+mpl_finance画K线图_第2张图片

4、画K线图(通过调用mpf.candlestick2_ochl()函数进行画K线图,这个函数的参数设置依照就可以,如果想更具体的了解可以自行百度了解一下)

fig, ax= plt.subplots(1, 1, sharex=True, figsize=(15, 10))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
mpf.candlestick2_ochl(ax,df["开始"], df["结束"], df["最高"], df["最低"], width=0.6, colorup='r',colordown='green',alpha=1.0)
plt.title('K线图')

结果图:使用Python pandas+matplotlib+mpl_finance画K线图_第3张图片 

完整版代码(本地测试可以运行):

# coding=utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mpl_finance as mpf
import warnings
d = {'最高':[132,135,136,137,139,136,132,130,130,134,135,132,132,137,138,136,136,140,122,138,135,142,141,144,144,139],
     '最低':[120,120,110,119,120,119,110,88,120,115,100,110,110,115,121,124,81,124,122,118,108,100,110,93,100,119],
     '开始':[127,126,124,133,126,120,119,125,123,122,127,123,127,128,127,128,81,132,127,129,125,129,132,93,133,119],
     '结束':[126,130,132,126,130,125,125,91,126,126,116,126,126,128,127,126,131,129,122,125,108,131,135,134,119,128]
    }
df = pd.DataFrame(d)
fig, ax= plt.subplots(1, 1, sharex=True, figsize=(15, 10))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
mpf.candlestick2_ochl(ax,df["开始"], df["结束"], df["最高"], df["最低"], width=0.6, colorup='r',colordown='green',alpha=1.0)
plt.title('K线图')

 

 

 

 

你可能感兴趣的:(Python数据分析学习笔记,python,pandas,matplotlib)