一、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. C++ #include " " 与 <>有什么区别?

    #include <> 和 #include "" 都会在实现定义的位置查找文件,并将其包含. 区别是若 #include "" 查找成功,则遮蔽 ...

  2. COCO2018 全景分割

    全景分割是18年新推出的一个任务,它要求同时分割出目标和背景,也就是既有实例分割也有语义分割,用官方的话讲是朝着真实世界视觉系统的重要一步 如图所示,里面既有对天空,草地等stuff的分割,也有对目标 ...

  3. django中的setting最佳配置小结

    Django settings详解 1.基础 DJANGO_SETTING_MODULE环境变量:让settings模块被包含到python可以找到的目录下,开发情况下不需要,我们通常会在当前文件夹运 ...

  4. Chrome浏览器如何完美实现滚动截图技巧

    一.前言 我们平时在浏览网页时,想把碰到好的网页内容或者文章截屏保存,但是网页的长度常常会超出屏幕高度,一般的截屏功能只能截取显示在屏幕上的内容,那我们该如何方便快捷截取全部内容?今天就分享一个如何利 ...

  5. Android RecyclerView组件和 Spinner(下拉列表框)

    1.RecyclerView <1>知识点介绍 RecyclerView 比 ListView 更高级且更具灵活性. 它是一个用于显示庞大数据集的容器,可通过保持有限数量的视图进行非常有效 ...

  6. 浏览器端 禁止 html 使用后退 或者替换后退功能..

    知乎大佬的代码: 作者:独夜行 链接:https://www.zhihu.com/question/40511430/answer/166467343 来源:知乎 著作权归作者所有.商业转载请联系作者 ...

  7. FTP 两种连接模式

    简介 FTP协议要用到两个TCP连接, 一个是命令连接,用来在FTP客户端与服务器之间传递命令:另一个是数据连接,用来上传或下载数据.通常21端口是命令端口,20端口是数据端口.当混入主动/被动模式的 ...

  8. 洛谷 P2048 BZOJ 2006 [NOI2010]超级钢琴

    题目描述 小Z是一个小有名气的钢琴家,最近C博士送给了小Z一架超级钢琴,小Z希望能够用这架钢琴创作出世界上最美妙的音乐. 这架超级钢琴可以弹奏出n个音符,编号为1至n.第i个音符的美妙度为Ai,其中A ...

  9. 109th LeetCode Weekly Contest Knight Dialer

    A chess knight can move as indicated in the chess diagram below:  .            This time, we place o ...

  10. TensorFlow-简单的卷积神经网络

    先弄懂卷积神经网络的原理,推荐这两篇博客:http://blog.csdn.net/yunpiao123456/article/details/52437794   http://blog.csdn. ...