python3.7对应的matplotlib版本(零基础入门到精通)
python3.7对应的matplotlib版本(零基础入门到精通)import matplotlib.pyplot as plt绘图实战引入matplotlib.pyplot或pip install matplotlib官网(matplotlib.org)在官网你可以找到matplotlib介绍和官方提供的安装教程。和一些文档链接。大部分重要的资源在gallery,在这里你能找到各种plot名称,例子,相关代码。
Matplotlib介绍matplotlib是最流行的Python绘图库,能够很好的控制图形的所有方位,它被设计成和Matlab中的plot一样的感觉。
Matplotlib对Pandas和Numpy Array的支持非常好。
安装在命令行或终端执行
conda install matplotlib
或
pip install matplotlib
官网(matplotlib.org)在官网你可以找到matplotlib介绍和官方提供的安装教程。和一些文档链接。大部分重要的资源在gallery,在这里你能找到各种plot名称,例子,相关代码。
绘图实战引入matplotlib.pyplot
import matplotlib.pyplot as plt
设置notebook使得plot绘图内容能够在jupyter notebook中显示
%matplotlib inline
定义一条曲线import numpy as np
x = np.linspace(0 5 11)
y = x ** 2
x
y
基础Matplotlib命令:
plt.plot(x y 'r') # 'r' is the color red
plt.xlabel('X Axis Title Here')
plt.ylabel('Y Axis Title Here')
plt.title('String Title Here')
plt.show()
如果你用过Matlab,这些命令你都会很熟悉。
# plt.subplot(nrows ncols plot_number)
plt.subplot(1 2 1)
plt.plot(x y 'r--') # More on color options later
plt.subplot(1 2 2)
plt.plot(y x 'g*-');
Matplotlib面向对象的用法:
# Create Figure (empty canvas)
fig = plt.figure()
# Add set of axes to figure
axes = fig.add_axes([0.1 0.1 0.8 0.8]) # left bottom width height (range 0 to 1)
# Plot on that set of axes
axes.plot(x y 'b')
axes.set_xlabel('Set X Label') # Notice the use of set_ to begin methods
axes.set_ylabel('Set y Label')
axes.set_title('Set Title')
figure画中画# Creates blank canvas
fig = plt.figure()
axes1 = fig.add_axes([0.1 0.1 0.8 0.8]) # main axes
axes2 = fig.add_axes([0.2 0.5 0.4 0.3]) # inset axes
# Larger Figure Axes 1
axes1.plot(x y 'b')
axes1.set_xlabel('X_label_axes2')
axes1.set_ylabel('Y_label_axes2')
axes1.set_title('Axes 2 Title')
# Insert Figure Axes 2
axes2.plot(y x 'r')
axes2.set_xlabel('X_label_axes2')
axes2.set_ylabel('Y_label_axes2')
axes2.set_title('Axes 2 Title');
plt.subplots()的作用像是一个坐标轴管理器
基本用法:
# Use similar to plt.figure() except use tuple unpacking to grab fig and axes
fig axes = plt.subplots()
# Now use the axes object to add stuff to plot
axes.plot(x y 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
你可以设置行和列:
# Empty canvas of 1 by 2 subplots
fig axes = plt.subplots(nrows=1 ncols=2)
# Axes is an array of axes to plot on
axes
我们可以遍历这个数组
for ax in axes:
ax.plot(x y 'b')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')
# Display the figure object
fig
函数fig.tight_layout() or plt.tight_layout()可以自动调节图形布局:
fig axes = plt.subplots(nrows=1 ncols=2)
for ax in axes:
ax.plot(x y 'g')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('title')
fig
plt.tight_layout()
Figure的大小,宽高比,DPI
Figure对象创建的时候可以设置figsize 和 dpi
figsize是包含width和height的元组
dpi是dots-per-inch的缩写,是每英寸包含多少像素点的意思。
例如:
fig = plt.figure(figsize=(8 4) dpi=100)
subplot也有同样用法:
fig axes = plt.subplots(figsize=(12 3))
axes.plot(x y 'r')
axes.set_xlabel('x')
axes.set_ylabel('y')
axes.set_title('title');
Figure对象通过savefig函数保存图形文件,支持的格式有:PNG JPG EPS SVG PGF and PDF
fig.savefig("filename.png")
同时保存的时候可以设置DPI
fig.savefig("filename.png" dpi=200)
图例,标签和标题
设置标题ax.set_title("title");
设置坐标轴标签ax.set_xlabel("x")
ax.set_ylabel("y");
设置图例fig = plt.figure()
ax = fig.add_axes([0 0 1 1])
ax.plot(x x**2 label="x**2")
ax.plot(x x**3 label="x**3")
ax.legend()
loc参数代表图例位置:
# Lots of options....
ax.legend(loc=1) # upper right corner
ax.legend(loc=2) # upper left corner
ax.legend(loc=3) # lower left corner
ax.legend(loc=4) # lower right corner
# .. many more options are available
# Most common to choose
ax.legend(loc=0) # let matplotlib decide the optimal location
fig
设置颜色,线条宽度,线条样式颜色# MATLAB style line color and style
fig ax = plt.subplots()
ax.plot(x x**2 'b.-') # blue line with dots
ax.plot(x x**3 'g--') # green dashed line
fig ax = plt.subplots()
ax.plot(x x 1 color="blue" alpha=0.5) # half-transparant
ax.plot(x x 2 color="#8B008B") # RGB hex code
ax.plot(x x 3 color="#FF8C00") # RGB hex code
线条和标记点样式
fig ax = plt.subplots(figsize=(12 6))
ax.plot(x x 1 color="red" linewidth=0.25)
ax.plot(x x 2 color="red" linewidth=0.50)
ax.plot(x x 3 color="red" linewidth=1.00)
ax.plot(x x 4 color="red" linewidth=2.00)
# possible linestype options ‘-‘ ‘–’ ‘-.’ ‘:’ ‘steps’
ax.plot(x x 5 color="green" lw=3 linestyle='-')
ax.plot(x x 6 color="green" lw=3 ls='-.')
ax.plot(x x 7 color="green" lw=3 ls=':')
# custom dash
line = ax.plot(x x 8 color="black" lw=1.50)
line.set_dashes([5 10 15 10]) # format: line length space length ...
# possible marker symbols: marker = ' ' 'o' '*' 's' ' ' '.' '1' '2' '3' '4' ...
ax.plot(x x 9 color="blue" lw=3 ls='-' marker=' ')
ax.plot(x x 10 color="blue" lw=3 ls='--' marker='o')
ax.plot(x x 11 color="blue" lw=3 ls='-' marker='s')
ax.plot(x x 12 color="blue" lw=3 ls='--' marker='1')
# marker size and color
ax.plot(x x 13 color="purple" lw=1 ls='-' marker='o' markersize=2)
ax.plot(x x 14 color="purple" lw=1 ls='-' marker='o' markersize=4)
ax.plot(x x 15 color="purple" lw=1 ls='-' marker='o' markersize=8 markerfacecolor="red")
ax.plot(x x 16 color="purple" lw=1 ls='-' marker='s' markersize=8
markerfacecolor="yellow" markeredgewidth=3 markeredgecolor="green");
控制坐标轴取值范围
fig axes = plt.subplots(1 3 figsize=(12 4))
axes[0].plot(x x**2 x x**3)
axes[0].set_title("default axes ranges")
axes[1].plot(x x**2 x x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")
axes[2].plot(x x**2 x x**3)
axes[2].set_ylim([0 60])
axes[2].set_xlim([2 5])
axes[2].set_title("custom axes range");
一些特殊的Plot样式
离散量
plt.scatter(x y)
直方图
from random import sample
data = sample(range(1 1000) 100)
plt.hist(data)
矩形
data = [np.random.normal(0 std 100) for std in range(1 4)]
# rectangular box plot
plt.boxplot(data vert=True patch_artist=True);
本系列文章共分为26个部分目前已经进行到了第8部分,所有内容计划如下:
- 预热
- 环境搭建
- Jupyter教程
- Python速成
- Python数据分析,NumPy库的使用
- Python数据分析,Pandas库的使用
- Python数据分析,Pandas库练习
- Python数据可视化,Matplotlib
- Python数据可视化,Seaborn
- Python数据可视化,Pandas内建数据可视化
- Python数据可视化,Plotly和Cufflinks
- Python数据可视化,Geographical Plotting
- 数据 Capstone 项目
- 机器学习介绍
- 线性回归
- 交叉验证与偏方差
- 逻辑回归算法
- k-近邻算法
- 决策树与随机森林
- 支持向量机
- k-means聚类
- 主成分分析
- 推荐系统
- 自然语言处理(NLP)
- Python大数据与Spark
- 神经网络(NN)与深度学习(DL)