Python Matplotlib
最后修改于 2024 年 1 月 29 日
本文介绍如何使用 Matplotlib 在 Python 中创建图表。我们将创建散点图、折线图、条形图和饼图。
Matplotlib
Matplotlib 是一个用于创建图表的 Python 库。Matplotlib 可用于 Python 脚本、Python 和 IPython shell、jupyter notebook、Web 应用程序服务器和四个图形用户界面工具包。
Matplotlib 安装
Matplotlib 是一个需要安装的外部 Python 库。
$ pip install matplotlib
我们可以使用 pip 工具来安装该库。
Matplotlib 散点图
散点图 是一种图表或数学图,它使用笛卡尔坐标来显示一组数据中通常两个变量的值。
#!/usr/bin/python
import matplotlib.pyplot as plt
x_axis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_axis = [5, 16, 34, 56, 32, 56, 32, 12, 76, 89]
plt.title("Prices over 10 years")
plt.scatter(x_axis, y_axis, color='darkblue', marker='x', label="item 1")
plt.xlabel("Time (years)")
plt.ylabel("Price (dollars)")
plt.grid(True)
plt.legend()
plt.show()
该示例绘制了一个散点图。该图表显示了某种商品在十年期间的价格。
import matplotlib.pyplot as plt
我们从 matplotlib 模块导入 pyplot。它是一个命令式函数集合,用于创建图表。它的操作方式与 MATLAB 类似。
x_axis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y_axis = [5, 16, 34, 56, 32, 56, 32, 12, 76, 89]
我们有 x 轴和 y 轴的数据。
plt.title("Prices over 10 years")
使用 title 函数,我们为图表设置标题。
plt.scatter(x_axis, y_axis, color='darkblue', marker='x', label="item 1")
scatter 函数绘制散点图。它接受 x 轴和 y 轴的数据、标记颜色、标记形状和标签。
plt.xlabel("Time (years)")
plt.ylabel("Price (dollars)")
我们设置轴的标签。
plt.grid(True)
我们使用 grid 函数显示网格。网格由若干垂直和水平线组成。
plt.legend()
legend 函数在轴上放置图例。
plt.show()
show 函数显示图表。
Mathplotlib 两个数据集
在下一个示例中,我们向图表添加另一个数据集。
#!/usr/bin/python
import matplotlib.pyplot as plt
x_axis1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_axis1 = [5, 16, 34, 56, 32, 56, 32, 12, 76, 89]
x_axis2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_axis2 = [53, 6, 46, 36, 15, 64, 73, 25, 82, 9]
plt.title("Prices over 10 years")
plt.scatter(x_axis1, y_axis1, color='darkblue', marker='x', label="item 1")
plt.scatter(x_axis2, y_axis2, color='darkred', marker='x', label="item 2")
plt.xlabel("Time (years)")
plt.ylabel("Price (dollars)")
plt.grid(True)
plt.legend()
plt.show()
该图表显示两个数据集。我们通过标记的颜色来区分它们。
x_axis1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y_axis1 = [5, 16, 34, 56, 32, 56, 32, 12, 76, 89] x_axis2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y_axis2 = [53, 6, 46, 36, 15, 64, 73, 25, 82, 9]
我们有两个数据集。
plt.scatter(x_axis1, y_axis1, color='darkblue', marker='x', label="item 1") plt.scatter(x_axis2, y_axis2, color='darkred', marker='x', label="item 2")
我们为每个集合调用 scatter 函数。
Matplotlib 折线图
折线图 是一种图表,它将信息显示为一系列称为标记的数据点,这些数据点由直线段连接。
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2.5 * np.pi * t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('Sine Wave')
plt.grid(True)
plt.show()
该示例显示了一个正弦波折线图。
import numpy as np
在该示例中,我们还需要 numpy 模块。
t = np.arange(0.0, 3.0, 0.01)
arange 函数返回给定间隔内均匀分布的值列表。
s = np.sin(2.5 * np.pi * t)
我们获得数据的 sin 值。
plt.plot(t, s)
我们使用 plot 函数绘制折线图。
Matplotlib 条形图
条形图 使用矩形条呈现分组数据,条的长度与它们所代表的值成比例。这些条可以垂直或水平绘制。
#!/usr/bin/python
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')
x = [0, 1, 2, 3, 4, 5]
y = [46, 38, 29, 22, 13, 11]
fig, ax = plt.subplots()
ax.bar(x, y, align='center')
ax.set_title('Olympic Gold medals in London')
ax.set_ylabel('Gold medals')
ax.set_xlabel('Countries')
ax.set_xticks(x)
ax.set_xticklabels(("USA", "China", "UK", "Russia",
"South Korea", "Germany"))
plt.show()
该示例绘制了一个条形图。它显示了 2012 年伦敦奥运会每个国家/地区的奥运金牌数。
style.use('ggplot')
可以使用预定义的样式。
fig, ax = plt.subplots()
subplots 函数返回一个 figure 和一个 axes 对象。
ax.bar(x, y, align='center')
使用 bar 函数生成条形图。
ax.set_xticks(x)
ax.set_xticklabels(("USA", "China", "UK", "Russia",
"South Korea", "Germany"))
我们为 x 轴设置国家/地区名称。
Matplotlib 饼图
饼图 是一种圆形图,它被分成多个扇形,以说明数值比例。
#!/usr/bin/python
import matplotlib.pyplot as plt
labels = ['Oranges', 'Pears', 'Plums', 'Blueberries']
quantity = [38, 45, 24, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
plt.pie(quantity, labels=labels, colors=colors, autopct='%1.1f%%',
shadow=True, startangle=90)
plt.axis('equal')
plt.show()
该示例创建了一个饼图。
labels = ['Oranges', 'Pears', 'Plums', 'Blueberries'] quantity = [38, 45, 24, 10]
我们有标签和相应的数量。
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
我们定义饼图切片的颜色。
plt.pie(quantity, labels=labels, colors=colors, autopct='%1.1f%%',
shadow=True, startangle=90)
使用 pie 函数生成饼图。autopct 负责在图表的楔形中显示百分比。
plt.axis('equal')
我们设置相等的纵横比,以便将饼图绘制成圆形。
饼图分离
我们可以通过分离视觉上分离一个或多个切片。
#!/usr/bin/python
import matplotlib.pyplot as plt
labels = ['FreeBSD', 'NetBSD', 'Linux', 'Window', 'Apple']
quantity = [4, 3, 12, 6, 2]
explodes = [0.2, 0, 0, 0, 0]
plt.pie(quantity, labels=labels, explode=explodes, autopct='%1.1f%%')
plt.axis('equal')
plt.savefig('piechart3.png')
在该示例中,我们首先将项目与其他项目分开。
来源
在本文中,我们使用 Matplotlib 库创建了散点图、折线图、条形图和饼图。
作者
列出所有 Python 教程。