Python学习第三十二天,matplotlib库学习(六)

96 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情

绘制多个子图

有时,并排比较不同的数据视图会很有帮助。为此,Matplotlib具有子图的概念:可以在单个图中一起存在的较小轴组。这些子图可能是插图,图形网格或其他更复杂的布局。

函数:

plt.subplot:子图的简单网格

代码:

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return np.exp(-t) * np.sin(2 * np.pi * t)

t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)

plt.figure(12)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')

plt.subplot(222)
plt.plot(t2, np.cos(2 * np.pi * t2), 'g--')

plt.subplot(212)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

plt.show()

结果:

image.png

三维散点图

三维的图会有助于我们从另一个角度认识我们的数据。

代码:

from mpl_toolkits import mplot3d
import matplotlib.pyplot as plt
import numpy as np
# Creating random dataset
z = 4 * np.tan(np.random.randint(10, size =(500))) + np.random.randint(100, size =(500))
x = 4 * np.cos(z) + np.random.normal(size = 500)
y = 4 * np.sin(z) + 4 * np.random.normal(size = 500)
# Creating figure
fig = plt.figure(figsize = (16, 12))
ax = plt.axes(projection ="3d")
# Add x, and y gridlines for the figure
ax.grid( color ='b',linestyle ='-.', linewidth = 0.5,alpha = 0.3)
# Creating the color map for the plot
my_cmap = plt.get_cmap('hsv')
# Creating the 3D plot
sctt = ax.scatter3D(x, y, z,alpha = 0.8,c = (x + y + z),cmap = my_cmap,marker ='^')
plt.title("3D scatter plot in Python")
ax.set_xlabel('X-axis', fontweight ='bold')
ax.set_ylabel('Y-axis', fontweight ='bold')
ax.set_zlabel('Z-axis', fontweight ='bold')
fig.colorbar(sctt, ax = ax, shrink = 0.6, aspect = 5)
# display the plot
plt.show()

结果: image.png

三维直线图

代码:

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()

结果:

image.png