Matplotlib是一个用于在Python中绘制数组的图形库,它提供了MATLAB风格的绘图功能。Matplotlib可以创建静态、动态和交互式的可视化,并支持多种输出格式和交互环境。Matplotlib还有丰富的颜色和色彩映射选项,可以自定义和美化图形。
本文介绍一下Matplotlib的基础画图案例。
折线图
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('A simple sine wave')
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
plt.fill_between(x, y1, y2,
where=(y1 > y2),
color='green',
alpha=0.5,
label='sin(x) > cos(x)')
plt.fill_between(x, y1, y2,
where=(y1 < y2),
color='red',
alpha=0.5,
label='sin(x) < cos(x)')
plt.xlabel('x')
plt.ylabel('y')
plt.title('A line plot with filled area')
plt.legend()
plt.show()
散点图
import matplotlib.pyplot as plt
import numpy as np
x1 = np.random.randn(100)
y1 = np.random.randn(100)
x2 = np.random.randn(100) + 3
y2 = np.random.randn(100) + 3
plt.scatter(x1, y1, label='Group A')
plt.scatter(x2, y2, label='Group B')
plt.xlabel('x')
plt.ylabel('y')
plt.title('A scatter plot with labels and legend')
plt.legend()
plt.show()
直方图
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
labels = ['Apple', 'Banana', 'Orange', 'Pear']
values = [10, 20, 15, 25]
plt.bar(labels, values)
cursor = Cursor(plt.gca(), horizOn=True, color='r', lw=1)
plt.xlabel('Fruits')
plt.ylabel('Quantity')
plt.title('A bar chart with cursor')
plt.show()
饼图
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]
explode = (0.1, 0.1, 0.1, 0.1)
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax1.pie(sizes,
labels=labels,
explode=explode,
autopct='%1.1f%%',
shadow=True,
startangle=90)
ax1.set_title('A pie chart with explode')
ax2.pie(sizes,
labels=labels,
autopct='%1.1f%%',
shadow=False,
startangle=90)
ax2.set_title('A pie chart without explode')
fig.show()
import matplotlib.pyplot as plt
sizes = [12, 23, 11, 17, 19, 24, 29, 11, 12, 9, 7, 5, 3, 2, 1]
labels = ["Market %s" % i for i in sizes]
fig1, ax1 = plt.subplots(figsize=(5, 5))
fig1.subplots_adjust(0.3, 0, 1, 1)
theme = plt.get_cmap('copper')
ax1.set_prop_cycle("color", [theme(1. * i / len(sizes))
for i in range(len(sizes))])
_, _ = ax1.pie(sizes, startangle=90, radius=1800)
ax1.axis('equal')
total = sum(sizes)
plt.legend(
loc='upper left',
labels=['%s, %1.1f%%' % (
l, (float(s) / total) * 100)
for l, s in zip(labels, sizes)],
prop={'size': 11},
bbox_to_anchor=(0.0, 1),
bbox_transform=fig1.transFigure
)
plt.show()
三维折线图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
t = np.linspace(0, 10, 100)
x = np.sin(t)
y = np.cos(t)
z = t
ax.plot(x,y,z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('A 3D line plot')
plt.show()
三维散点图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.random.randn(100)
y = np.random.randn(100)
z = np.random.randn(100)
ax.scatter(x,y,z,c=z,s=50,cmap=plt.cm.jet)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('A 3D scatter plot')
plt.show()
三维柱状图
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
xpos = [1,2,3]
ypos = [1,2,3]
zpos = [0,0,0]
dx = [1]*len(xpos)
dy = [1]*len(ypos)
dz =[10]*len(zpos)
colors=['r','g','b']
for i in range(len(xpos)):
ax.bar3d(xpos[i], ypos[i], zpos[i], dx[i], dy[i], dz[i], color=colors[i])
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_title('A 3D bar chart')
plt.show()
气泡图
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
N = 50
M = 5 # Number of bins
x = np.random.rand(N)
y = np.random.rand(N)
a2 = 400*np.random.rand(N)
# Create the DataFrame from your randomised data and bin it using groupby.
df = pd.DataFrame(data=dict(x=x, y=y, a2=a2))
bins = np.linspace(df.a2.min(), df.a2.max(), M)
grouped = df.groupby(np.digitize(df.a2, bins))
# Create some sizes and some labels.
sizes = [50*(i+1.) for i in range(M)]
labels = ['Tiny', 'Small', 'Medium', 'Large', 'Huge']
for i, (name, group) in enumerate(grouped):
plt.scatter(group.x, group.y, s=sizes[i], alpha=0.5, label=labels[i])
plt.legend()
plt.show()
多图合一
要用matplotlib画一个多图合一的案例,可以用以下几种方法。
方法一:用plt.subplots()函数来创建一个画布和多个子图,并返回一个fig对象和一个axs数组,然后用axs[i][j]来指定每个子图的位置和内容。
方法二:用plt.subplot()函数来在一个画布上创建多个子图,并传入行数、列数和索引参数来指定每个子图的位置,然后用plt.plot()等函数来绘制每个子图的内容。
方法三:用plt.subplot2grid()函数来在一个网格上创建多个子图,并传入网格大小、起始位置和占据大小等参数来指定每个子图的位置和大小,然后用plt.plot()等函数来绘制每个子图的内容。
方法四:用gridspec.GridSpec()类来创建一个网格规范对象,并传入行数、列数等参数来定义网格的结构,然后用plt.subplot()函数和gs[i,j]语法来创建多个子图并指定它们在网格中的位置。
import matplotlib.pyplot as plt
import numpy as np
# 生成随机数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
# 创建画布和4*4的子图数组
fig, axs = plt.subplots(4, 4)
# 在第一行第一列绘制正弦曲线
axs[0, 0].plot(x, y1)
axs[0, 0].set_title('sin(x)')
# 在第二行第二列绘制余弦曲线
axs[1, 1].plot(x, y2)
axs[1, 1].set_title('cos(x)')
# 在第三行第三列绘制正切曲线
axs[2, 2].plot(x, y3)
axs[2, 2].set_title('tan(x)')
# 调整子图间距
fig.tight_layout()
# 显示图形
plt.show()