Matplotlib 中的内联魔术函数
在此文章中,我们将了解什么是魔法函数,然后我们将看到 Matplotlib 中可用的不同魔法函数。 在此之后,我们讨论内联函数。
在 Matplotlib 中使用内联魔术函数
交互式 Python 提供了几个预定义的函数,称为魔法函数,这些魔法函数可以通过命令行和样式语法调用。 魔术函数有两种类型,称为面向行的和面向单元的。
面向行的也称为行魔术,这些函数以 % 符号开头,后面是行的其余部分的参数,没有任何引号或括号。 如果我们在交互式 Python 中,我们也可以说“ipython”会话,意思是 jupyter notebook。
下面是调用函数的语法。
%matplotlib [gui]
这里的 [gui]
是要通过调用函数启用的 Matplotlib 后端的名称。 如果我们想查看可用的 Matplotlib 包列表,我们应该使用以下命令。
命令:
%matplotlib -l
输出:
Available matplotlib backends: ['tk', 'gtk', 'gtk3', 'gtk4', 'wx', 'qt4', 'qt5', 'qt6', 'qt', 'osx', 'nbagg', 'notebook', 'agg', 'svg', 'pdf', 'ps', 'inline', 'ipympl', 'widget']
下面的命令是另一种检查方法,它也会显示与上面相同的结果。
%matplotlib --list
现在我们将讨论魔术函数 %matplotlib inline
以启用内联绘图,其中绘图和图形将显示在单元格下方。 假设我们想通过使用颜色图更改绘图的颜色,它不会影响以前的绘图。
让我们学习如何在 jupyter notebook 中使用这个内联函数,下面是示例。 如果我们执行这个程序,你会在这里看到情节,我们可以看到它的样子。
代码:
from matplotlib import pyplot as plt
%matplotlib inline
x1 = [1,5,8,11,14,11]
y1 = [12,11,15,1,22,15]
y2 = [10,12,15,10,20,10]
y3 = [11,9,15,10,12,14]
plt.figure(figsize=[9, 7])
plt.title('%matplotlib inline')
plt.plot(x1, y1, linewidth=2, label='sin()')
plt.plot(x1, y2, linewidth=2, label='cos()')
plt.plot(x1, y3, linewidth=2, label='tan()')
输出:
如果您使用的是当前版本的 ipython notebook
和 jupyter notebook
,则无需使用 inline 函数。 无论是否调用 Matplotlib 的 show() 函数,图形输出都会显示。
代码:
from matplotlib import pyplot as plt
x1 = [1,5,8,11,14,11]
y1 = [12,11,15,1,22,15]
y2 = [10,12,15,10,20,10]
y3 = [11,9,15,10,12,14]
plt.figure(figsize=[9, 7])
plt.title('%matplotlib inline')
plt.plot(x1, y1, linewidth=2, label='sin()')
plt.plot(x1, y2, linewidth=2, label='cos()')
plt.plot(x1, y3, linewidth=2, label='tan()')
如果你试图在 pycharm 中内联使用这个 Matplotlib,它会显示语法错误,但如果你想在 Visual Studio 中使用它,你需要添加扩展名“jupyter note”。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串