一、Matplotlib介绍

  Matplotlib是一个强大的Python**绘图**和**数据可视化**的工具包。

# 安装方法
pip install matplotlib
# 引用方法
import matplotlib.pyplot as plt # 绘图函数
plt.plot()
# 展示图像
plt.show()

  执行后显示效果如下:

  

二、plot函数使用

  plot函数:用于绘制折线图。

1、绘制线型图

  线型linestyle:‘-’是实线、'--'是线虚线、‘-.’是线点虚线等、‘:’是点虚线。

import matplotlib.pyplot as plt

plt.plot([1,2,3,4],[2,3,1,8])  # 绘制折线图
plt.show()

  显示效果如下所示:

  

2、绘制点型图

  点型marker:v、^、s、*、H、+、x、D、o.....

  其中是o是圆点、v是下三角、D是菱形、H是六边形等。

(1)绘制点图

plt.plot([1,2,3,4],[2,3,1,8], 'o')  # 参数o,绘制点图
plt.show()

  显示效果如下所示:

  

(2)绘制点线图

plt.plot([1,2,3,4],[2,3,1,8], 'o-')  # 参数o-,绘制点线图
plt.show()

  显示效果如下所示:

  

3、绘图颜色

  颜色color:b、g、r、y、k、w......

(1)方法一:配合线设置颜色

plt.plot([1,2,3,4],[2,3,2,7], 'o:r')   # 红色线
plt.show()

  显示效果如下所示:

  

(2)方法二:用color参数设置颜色

plt.plot([1,2,3,4],[2,3,2,7], color='purple')   # 紫色线
plt.show()

  显示效果如下所示:

  

4、plot函数绘制多条曲线

  生成几个plot.plot()就可以在一个图里绘制多少个曲线。

plt.plot([1,2,3,4],[2,3,2,7], color='red')
plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o')
plt.show()

  显示效果如下所示:

  

三、图像标注

  前面学习的plt.plot()和plt.show()函数只是绘图和显示图像。但如果要设置标题、名称等图像标注就需要用到其他函数了。

  • 设置图像标题:plt.title()
  • 设置x轴名称:plt.xlabel()
  • 设置y轴名称:plt.ylabel()
  • 设置x轴范围:plt.xlim()
  • 设置y轴范围:plt.ylim()
  • 设置x轴刻度:plt.xticks()
  • 设置y轴刻度:plt.yticks()
  • 设置曲线图例:plt.legend()

1、设置图像标题

# 引用方法
import matplotlib.pyplot as plt # 绘图函数
plt.plot([1,2,3,4],[2,3,2,7], color='red')
plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o')
plt.title('Matplotlib Test Plot') # 设置图像标题 # 展示图像
plt.show()

  显示效果如下所示:

  

2、设置xy轴名称

# 引用方法
import matplotlib.pyplot as plt # 绘图函数
plt.plot([1,2,3,4],[2,3,2,7], color='red')
plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o')
plt.title('Matplotlib Test Plot')
plt.xlabel('Xlabel')
plt.ylabel('Ylabel') # 展示图像
plt.show()

  显示效果如下所示:

  

3、设置xy轴范围

# 引用方法
import matplotlib.pyplot as plt # 绘图函数
plt.plot([1,2,3,4],[2,3,2,7], color='red')
plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o')
plt.title('Matplotlib Test Plot')
plt.xlabel('Xlabel')
plt.ylabel('Ylabel')
plt.xlim(0,5) # 设置x轴最小值0,最大值5
plt.ylim(0,10) # 设置y轴最小值0,最大值10 # 展示图像
plt.show()

  显示效果如下所示:

  

4、设置xy轴刻度

# 引用方法
import matplotlib.pyplot as plt
import numpy as np # 绘图函数
plt.plot([1,2,3,4],[2,3,2,7], color='red')
plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o')
plt.title('Matplotlib Test Plot')
plt.xlabel('Xlabel')
plt.ylabel('Ylabel')
plt.xlim(0,10)
plt.ylim(0,10)
# plt.xticks(0,2,4) # 设置x轴刻度
plt.xticks(np.arange(0,11,2)) # 用numpy设置x轴刻度 # 展示图像
plt.show()

  显示效果如下所示:

  

  刻度还可以自定义字段显示:

# 引用方法
import matplotlib.pyplot as plt
import numpy as np # 绘图函数
plt.plot([1,2,3,4],[2,3,2,7], color='red')
plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o')
plt.title('Matplotlib Test Plot')
plt.xlabel('Xlabel')
plt.ylabel('Ylabel')
plt.xlim(0,10)
plt.ylim(0,10)
# plt.xticks(0,2,4) # 设置x轴刻度
plt.xticks(np.arange(0,11,2), ['a','b','c','d','e','f']) # 用numpy设置x轴刻度 # 展示图像
plt.show()

  显示效果如下:

  

5、设置曲线图例

  在plt.plot()中设置label,即可使用plt.legend()函数设置曲线图例。

# 引用方法
import matplotlib.pyplot as plt
import numpy as np # 绘图函数
plt.plot([1,2,3,4],[2,3,2,7], color='red', label='Line A')
plt.plot([1,2,3,4],[3,5,6,9], color='black',marker='o', label='Line B')
plt.title('Matplotlib Test Plot')
plt.xlabel('Xlabel')
plt.ylabel('Ylabel')
plt.legend() # 曲线图例 # 展示图像
plt.show()

  显示效果如下:

  

四、Matplotlib应用实例

1、pandas和matplotlib结合使用

import matplotlib.pyplot as plt
import pandas as pd df = pd.read_csv('601318.csv', parse_dates=['date'], index_col='date')[['open','close','high','low']] # 读取csv文件,使用date作为索引列
df.plot()
plt.show()

  显示效果如下所示:

  

2、绘制数学函数图像

  

# 引用方法
import matplotlib.pyplot as plt
import numpy as np x = np.linspace(-100,100,10000) # 起点、终点、分多少份
y1=x
y2=x**2
y3=3*(x**3)+5*(x**2)+2*x+1
plt.plot(x, y1, color='red', label='y=x')
plt.plot(x, y2, color='green', label='y=x**2')
plt.plot(x, y3, color='purple', label='y=3*(x**3)+5*(x**2)+2*x+1')
plt.ylim(-1000,1000) # 由于紫色线增长过快,图片显示会导致红色和绿色重合
plt.xlim(-100,100)
plt.legend() # 展示图像
plt.show()

  显示效果如下所示:

  

五、matplotlib绘制常用图表

  Matplotlib提供了很多函数来支持不同的图类型,如下所示:

函数 说明
plt.plot(x,y,fmt,...) 坐标图
plt.boxplot(data,notch,position) 箱型图

plt.bar(left,height,width,bottom)

条形图
plt.barh(width,bottom,left,height) 横向条形图
plt.polar(theta, r) 极坐标图
plt.pie(data, explode) 饼图
plt.psd(x,NFFT=256,pad_to,Fs) 功率谱密度图
plt.specgram(x,NFFT=256,pad_to,F) 谱图
plt.cohere(x,y,NFFT=256,Fs) X-Y相关性函数 
plt.scatter(x,y) 散点图
plt.step(x,y,where) 步阶图 
plt.hist(x,bins,normed) 直方图 

  相关文档参见:matplotlib官网

1、画布和子图

(1)子图并行排列

import matplotlib.pyplot as plt
import pandas as pd # 画布:figure
fig = plt.figure() # 生成画布
# 图:subplot
ax1 = fig.add_subplot(2,2,1) # 两行两列第一个图
ax1.plot([1,2,3,4],[5,6,7,8])
ax2 = fig.add_subplot(2,2,2) # 两行两列第二个图
ax2.plot([1,4,2,3],[2,6,3,8])
fig.show()

  显示效果如下所示:

  

(2)子图上下排列

import matplotlib.pyplot as plt
import pandas as pd # 画布:figure
fig = plt.figure() # 生成画布
# 图:subplot
ax1 = fig.add_subplot(2,1,1) # 两行一列第一个图
ax1.plot([1,2,3,4],[5,6,7,8])
ax2 = fig.add_subplot(2,1,2) # 两行一列第二个图
ax2.plot([1,4,2,3],[2,3,4,6])
fig.show()

  显示效果如下所示:

  

(3)用subplots_adjust()调节子图间距

  subplots_adjust()函数源码如下所示:

def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None):
"""
Update the :class:`SubplotParams` with *kwargs* (defaulting to rc when
*None*) and update the subplot locations. """
if self.get_constrained_layout():
self.set_constrained_layout(False)
warnings.warn("This figure was using constrained_layout==True, "
"but that is incompatible with subplots_adjust and "
"or tight_layout: setting "
"constrained_layout==False. ")
self.subplotpars.update(left, bottom, right, top, wspace, hspace)
for ax in self.axes:
if not isinstance(ax, SubplotBase):
# Check if sharing a subplots axis
if isinstance(ax._sharex, SubplotBase):
ax._sharex.update_params()
ax.set_position(ax._sharex.figbox)
elif isinstance(ax._sharey, SubplotBase):
ax._sharey.update_params()
ax.set_position(ax._sharey.figbox)
else:
ax.update_params()
ax.set_position(ax.figbox)
self.stale = True

  

2、柱状图和饼图

(1)柱状图基本示例

import matplotlib.pyplot as plt
import numpy as np data = [32,48,21,100]
labels = ['Jan', 'Feb', 'Mar', 'Apr'] # 柱状图
plt.bar(np.arange(len(data)), data , color='blue', width=0.5)
plt.xticks(np.arange(len(data)), labels)
plt.show()

  显示效果:

  

(2)饼图基本示例

import matplotlib.pyplot as plt

plt.pie([10,20,28,42], labels=['England','German','USA','China'], autopct='%.2f%%',explode=[0,0.1,0,0.1])
# labels设置标签,autopct显示百分比,explode设置突出程度
# plt.axis('equal') # 设置图片朝向
plt.show()

  显示效果:

  

3、绘制K线图

  matplotlib.finanace子包中有许多绘制金融相关图的函数接口。

  绘制K线图:matplotlib.finance.candlestick_ochl函数。

import matplotlib.finance as fin

  但是从matplotlib 2.2.0版本开始,matplotlib.finance已经从matplotlib中剥离了,需要单独安装mpl_finance这个包了。

  可以anaconda中下载mpl-finance包等方法下载。

import mpl_finance as fin

(1)candlestick_ochl()函数源码分析

def candlestick_ochl(ax, quotes, width=0.2, colorup='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 # datetime要转化为小数类型时间戳 width : float # k线宽度
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 """
return _candlestick(ax, quotes, width=width, colorup=colorup,
colordown=colordown,
alpha=alpha, ochl=True)

(2)date2num函数用于将datetime对象转化为浮点数表示的时间戳

def date2num(d):
"""
Convert datetime objects to Matplotlib dates. Parameters
----------
d : `datetime.datetime` or `numpy.datetime64` or sequences of these Returns
-------
float or sequence of floats
Number of days (fraction part represents hours, minutes, seconds, ms)
since 0001-01-01 00:00:00 UTC, plus one. Notes
-----
The addition of one here is a historical artifact. Also, note that the
Gregorian calendar is assumed; this is not universal practice.
For details see the module docstring.
"""
if hasattr(d, "values"):
# this unpacks pandas series or dataframes...
d = d.values
if not np.iterable(d):
if (isinstance(d, np.datetime64) or (isinstance(d, np.ndarray) and
np.issubdtype(d.dtype, np.datetime64))):
return _dt64_to_ordinalf(d)
return _to_ordinalf(d) else:
d = np.asarray(d)
if np.issubdtype(d.dtype, np.datetime64):
return _dt64_to_ordinalf(d)
if not d.size:
return d
return _to_ordinalf_np_vectorized(d)

(3)使用上述包绘制k线图示例

# import matplotlib.finance as fin

import pandas as pd
import matplotlib.pyplot as plt
import mpl_finance as fin
from matplotlib.dates import date2num # 用于将datetime对象转化为浮点数 # 读取csv文件中保存的行情数据,使用date作为索引列
# na_values将None字符串解释为缺失值
df = pd.read_csv('601318.csv', parse_dates=['date'], index_col='date', na_values=['None'])[['open','close','high','low']]
# 添加time这一列
df['time'] = date2num(df.index.to_pydatetime())
# 将df转换为数组才能传递给candlestick_ochl()函数
arr = df[['time','open','close','high','low']].values # print(df)
'''
open close high low time
date
2007-03-01 21.878 None 22.302 20.040 732736.0
2007-03-02 20.565 None 20.758 20.075 732737.0
'''
# 由于candlestick_ochl函数中要求有Axes,因此创建画布和子图
fig = plt.figure() # 画布
ax = fig.add_subplot(1,1,1) # 子图 # candlestick_ochl()与candlestick_ohlc()的区别主要是执行顺序
fin.candlestick_ochl(ax, arr)
# fig.grid()
fig.show()

  显示效果如下所示:

  

绘图和数据可视化工具包——matplotlib的更多相关文章

  1. 数据可视化之Matplotlib的使用

    1.什么是数据可视化 数据可视化在量化分析当中是一个非常关键的辅助工具,往往我们需要通过可视化技术,对我们的数据进行更清晰的展示,这样也能帮助我们理解交易.理解数据.通过数据的可视化也可以更快速的发现 ...

  2. Python数据可视化——使用Matplotlib创建散点图

    Python数据可视化——使用Matplotlib创建散点图 2017-12-27 作者:淡水化合物 Matplotlib简述: Matplotlib是一个用于创建出高质量图表的桌面绘图包(主要是2D ...

  3. python 数据可视化(matplotlib)

    matpotlib 官网 :https://matplotlib.org/index.html matplotlib 可视化示例:https://matplotlib.org/gallery/inde ...

  4. 学机器学习,不会数据分析怎么行——数据可视化分析(matplotlib)

    前言 前面两篇文章介绍了 python 中两大模块 pandas 和 numpy 的一些基本使用方法,然而,仅仅会处理数据还是不够的,我们需要学会怎么分析,毫无疑问,利用图表对数据进行分析是最容易的, ...

  5. Python数据可视化库-Matplotlib(一)

    今天我们来学习一下python的数据可视化库,Matplotlib,是一个Python的2D绘图库 通过这个库,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率图,条形图,错误图,散点图等等 废 ...

  6. Python数据可视化之Matplotlib实现各种图表

    数据分析就是将数据以各种图表的形式展现给领导,供领导做决策用,因此熟练掌握饼图.柱状图.线图等图表制作是一个数据分析师必备的技能.Python有两个比较出色的图表制作框架,分别是Matplotlib和 ...

  7. python的数据可视化库 matplotlib 和 pyecharts

    Matplotlib大家都很熟悉    不谈. ---------------------------------------------------------------------------- ...

  8. Python数据可视化利器Matplotlib,绘图入门篇,Pyplot介绍

    Pyplot matplotlib.pyplot是一个命令型函数集合,它可以让我们像使用MATLAB一样使用matplotlib.pyplot中的每一个函数都会对画布图像作出相应的改变,如创建画布.在 ...

  9. Python3 数据可视化之matplotlib、Pygal、requests

    matplotlib的学习和使用 matplotlib的安装 pip3 install matplotlib 简单的折线图 import matplotlib.pyplot as plt #绘制简单的 ...

随机推荐

  1. day--43 HTML标签和CSS基本小结

    HTML标签和CSS基本小结一:常用标签 01:块标签 p,h1--h6 ,hr ,div 02:内联标签 b,i,u,s 小提示:块标签可以嵌套内置元素或者某些块级元素,但内联元素不能包含块级元素 ...

  2. vcftools安装与使用

    官网地址:https://vcftools.github.io/examples.html vcftools的软件下载:https://vcftools.github.io/examples.html ...

  3. P4174 [NOI2006]最大获利

    传送门 把用户群和中转站都看成点 用户群权值为正,中转站权值为负 为了获得用户群的权值,我们不得不一起获得中转站负的权值 发现就是裸的最大权闭合子图 那么从用户群连边向中转站,边值INF 从 S 连向 ...

  4. leetcode 283 Move Zeros; 27 Remove Elements; 26 Remove Duplicated from Sorted Array;

    ,,,,}; //把数组的值赋给vector vector<int> vec(arr, arr+sizeof(arr)/sizeof(int)); 解法一: 时间复杂度O(n) 空间复杂度 ...

  5. apache 2.4 访问权限配置

    在apache 2.4里,访问权限配置与2.2不同,如果设置不对,则会报403错误,日志中会报 AH01630: client denied by server configuration.   [S ...

  6. 使用Tomcat搭建一个可以通过公网访问的服务器(转)

    转自:http://wenku.baidu.com/link?url=kGLhiO1xiiepXa9Q2OJDmm6Zr8dQmpSYYPVTFmc3CZtD6Z7HvFi2miCYDiQdTYF2T ...

  7. shell 操作符详解

     = 赋值操作符,可以用于算术和字符串赋值 +  加法计算   -  减法运算 *  乘法运算 /   除法运算 **  幂运算 % 模运算 取他除后的剩余数   因此这个十分好求公约数 += &qu ...

  8. 构建标准OpenStack API接口文档

    1.构建API接口文档标准参考: http://docs.openstack.org/contributor-guide/api-guides.html 2.构建API接口文档步骤参考下面的Patch ...

  9. (转)DB2中的一些函数

    DB2中的一些函数 原文:https://www.cnblogs.com/ShaYeBlog/archive/2012/08/27/2658025.html 最近用DB2,数据库之间的差异还是很大的, ...

  10. How to add more to Git Bash on Windows

    How to add more to Git Bash on Windows Download the lastest wget binary for windows from https://ete ...