介绍

官网:https://www.matplotlib.org.cn/intro/

说到Python数据可视化,不得不说的模块便是Matplotlib,其期初是模仿Matplotlib的方式开发的绘图模块,经过迭代已经可以成熟的对Numpy和Pandas进行兼容,使用起来方便而快捷。

Import the matplotlib.pyplot module

In [1]:
import matplotlib.pyplot as plt

输入下方的代码在notebook中显示图

In [2]:
%matplotlib inline
# 在notebook显示图
# That line is only for jupyter notebooks.
In [3]:
# 设置几个全局参数!
plt.style.use('bmh')
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12
plt.rcParams['text.color'] = 'k'
plt.rcParams['figure.figsize'] = 10,6

基础教程

获取更多【Matplotlib】的中高级教程,请进入👉传送门

x = 0 到 10 的整数

y = x 的平方

In [4]:
import numpy as np
x = np.linspace(0, 10, 11)
y = x ** 2
In [5]:
x
Out[5]:
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
In [6]:
y
Out[6]:
array([  0.,   1.,   4.,   9.,  16.,  25.,  36.,  49.,  64.,  81., 100.])

基本操作

创建第一个图(用 Shift+Tab 来检查函数帮助文档!)。

In [7]:
plt.plot(x, y, 'r--') # 'r' 红色 -- 代表虚线
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.title('标题')
plt.show()
C:\Users\gzjgz\anaconda3\lib\site-packages\IPython\core\pylabtools.py:132: UserWarning: Glyph 26631 (\N{CJK UNIFIED IDEOGRAPH-6807}) missing from current font.
  fig.canvas.print_figure(bytes_io, **kw)
C:\Users\gzjgz\anaconda3\lib\site-packages\IPython\core\pylabtools.py:132: UserWarning: Glyph 39064 (\N{CJK UNIFIED IDEOGRAPH-9898}) missing from current font.
  fig.canvas.print_figure(bytes_io, **kw)
C:\Users\gzjgz\anaconda3\lib\site-packages\IPython\core\pylabtools.py:132: UserWarning: Glyph 36724 (\N{CJK UNIFIED IDEOGRAPH-8F74}) missing from current font.
  fig.canvas.print_figure(bytes_io, **kw)

发现好像不能打中文啊,别着急,加上下面的代码就可以了!

In [8]:
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
In [9]:
plt.plot(x, y, 'r--') # 'r' 红色 -- 代表虚线
plt.xlabel('X 轴')
plt.ylabel('Y 轴')
plt.title('标题')
plt.show()

绘制多图(同一画布)

如果想在一个画布上画子图咋办,我们用 subplot!

In [10]:
# plt.subplot(nrows, ncols, plot_number)

plt.subplot(1,2,1) # 一行两列的第一个子图
plt.plot(x, y, 'r--') 
plt.subplot(1,2,2) # 一行两列的第一个子图
plt.plot(y, x, 'g*-');

如何更改画布大小?

In [11]:
plt.figure(figsize = [12,3])  # 更改画布大小


plt.subplot(1,2,1) # 一行两列的第一个子图
plt.plot(x, y, 'r--') 
plt.subplot(1,2,2) # 一行两列的第一个子图
plt.plot(y, x, 'g*-');

面向对象画图

现在我们已经了解了基础知识,让我们通过更正式的 Matplotlib 面向对象 API 的介绍来分解它。这意味着我们将实例化图形对象,然后从该对象调用方法或属性。

OOM介绍

使用更正式的面向对象方法的主要思想是创建图形对象,然后调用该对象的方法或属性。在处理上面有多个绘图的画布时,这种方法更好。

首先,我们创建一个图形实例。然后我们可以在该图中添加轴:

In [12]:
# 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')
Out[12]:
Text(0.5, 1.0, 'Set Title')

代码稍微复杂一点,但优点是我们现在可以完全控制绘图轴的放置位置,并且我们可以轻松地在图中添加多个轴:

In [13]:
# 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');

子图 subplots()

plt.subplots() 对象将充当更自动的【轴】管理器。

基本用例:

In [14]:
# 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');

Then you can specify the number of rows and columns when creating the subplots() object:

In [15]:
# Empty canvas of 1 by 2 subplots
fig, axes = plt.subplots(nrows=1, ncols=2)
In [16]:
# Axes is an array of axes to plot on
axes
Out[16]:
array([<AxesSubplot:>, <AxesSubplot:>], dtype=object)

We can iterate through this array:

In [17]:
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
Out[17]:

matplolib 的一个常见问题是子图或图形会重叠。

我们可以使用 fig.tight_layout()plt.tight_layout() 方法,它会自动调整轴在图形画布上的位置,以免内容重叠:

In [18]:
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()

基础属性

Matplotlib 允许在创建 Figure 对象时指定纵横比、DPI 和图形大小。您可以使用 figsizedpi 关键字参数。

  • figsize 是以英寸为单位的图形宽度和高度的元组
  • dpi 是每英寸点数(每英寸像素)。

例如:

In [19]:
fig = plt.figure(figsize=(8,4), dpi=100)
<Figure size 800x400 with 0 Axes>

相同的参数也可以传递给布局管理器,例如 subplots 函数:

In [20]:
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 方法:|

In [21]:
fig.savefig("filename.png")

Here we can also optionally specify the DPI and choose between different output formats:

In [22]:
fig.savefig("filename.png", dpi=200)

图例标签以及标题

现在我们已经介绍了如何创建图形画布和向画布添加轴实例的基础知识,让我们看看如何用标题、轴标签和图例装饰图形。

Figure titles

可以为图中的每个轴实例添加标题。要设置标题,请在坐标区实例中使用 set_title 方法:

In [23]:
ax.set_title("title");

Axis labels

同样,使用 set_xlabelset_ylabel 方法,我们可以设置 X 和 Y 轴的标签:

In [24]:
ax.set_xlabel("x")
ax.set_ylabel("y");

Legends

在将绘图或其他对象添加到图形时使用 label="label text" 关键字参数,然后使用不带参数的 legend 方法将图例添加到图形:

In [25]:
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()
Out[25]:
<matplotlib.legend.Legend at 0x2428d9b6508>

可能图例会和图形重叠!

legend 函数采用可选的关键字参数 loc,可用于指定要在图中的何处绘制图例。 loc 的允许值是可以绘制图例的各个位置的数字代码。有关详细信息,请参阅 文档页面。一些最常见的 loc 值是:

In [26]:
# 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=1) # let matplotlib decide the optimal location
fig
Out[26]:

颜色线型以及线宽

Matplotlib 提供了很多用于自定义颜色、线宽和线型的选项。

使用 matplotlib,我们可以通过多种方式定义线条和其他图形元素的颜色。首先,我们可以使用类似 MATLAB 的语法,其中“b”表示蓝色,“g”表示绿色等。还支持用于选择线型的 MATLAB API:例如,“b”。 -' 表示带点的蓝线:

In [27]:
# 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
Out[27]:
[<matplotlib.lines.Line2D at 0x2428da3c9c8>]

我们还可以通过名称或 RGB 十六进制代码定义颜色,并可选择使用 coloralpha 关键字参数提供 alpha 值。 Alpha 表示不透明度。

In [28]:
fig, ax = plt.subplots()

ax.plot(x, x+1, color="blue", alpha=0.1) # half-transparant
ax.plot(x, x+2, color="#8B008B")        # RGB hex code
ax.plot(x, x+3, color="#FF8C00")        # RGB hex code 
Out[28]:
[<matplotlib.lines.Line2D at 0x2428da6cdc8>]

自定义线和点

要更改线宽,我们可以使用 linewidthlw 关键字参数。可以使用 linestylels 关键字参数选择线条样式:

In [29]:
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");

轴属性

在本节中,我们将研究在 matplotlib 图中控制轴大小的属性。

范围

我们可以使用轴对象中的 set_ylimset_xlim 方法来配置轴的范围,或者使用 axis('tight') 来自动获取“紧密拟合”的轴范围:

In [30]:
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");

特殊图表

我们可以创建许多专门的图,例如条形图、直方图、散点图等等。我们将使用 seaborn(Python 的统计绘图库)实际创建大多数此类绘图。但这里有一些此类图的示例:

In [31]:
plt.scatter(x,y)
Out[31]:
<matplotlib.collections.PathCollection at 0x242d0b15408>
In [32]:
from random import sample
data = sample(range(1, 1000), 100)
plt.hist(data,bins = 20)
Out[32]:
(array([7., 7., 2., 3., 3., 6., 7., 6., 6., 5., 2., 3., 4., 5., 8., 5., 4.,
        4., 7., 6.]),
 array([  3.  ,  52.55, 102.1 , 151.65, 201.2 , 250.75, 300.3 , 349.85,
        399.4 , 448.95, 498.5 , 548.05, 597.6 , 647.15, 696.7 , 746.25,
        795.8 , 845.35, 894.9 , 944.45, 994.  ]),
 <BarContainer object of 20 artists>)
In [33]:
data = [np.random.normal(0, std, 100) for std in range(1, 4)]

# rectangular box plot
plt.boxplot(data,vert=True,patch_artist=True);   

其他资料

In [34]:
from IPython.display import IFrame

请观看下方视频,讲的不错,是个合集,右上角可以点击【播放列表】,加油!

In [35]:
IFrame(width="853",height="480",src = "https://www.youtube.com/embed/UO98lJQ3QGI?list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB_")
Out[35]:

想【免费】获取更多关于Matplotlib的详细资料嘛?

请关注我!

  • 公众号:鲸析
  • 小红书:鲸鲸说数据

只做不一样的内容!

更多内容:

请关注我的gitee,更多精彩内容等你挖掘!

👇👇👇

传送门