1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 使用Matplotlib在Python中绘制三维散点图

使用Matplotlib在Python中绘制三维散点图

时间:2022-04-24 22:12:41

相关推荐

使用Matplotlib在Python中绘制三维散点图

什么是Matplotlib?

Matplotlib是Python中的一个库,用于创建静态和动态动画,并使用其内置函数绘制。它有很多内置特性和内置分析工具,用于分析任何图形或图表。

如果我们想绘制任何三维图形,那么我们可以使用Matplotlib库。当我们有一个巨大的三维变量数据集,我们绘制它的图形时,它看起来非常分散,这被称为3D散点图。我们将使用Matplotlib的matplot3d工具包绘制三维图形。

有一把斧头。函数,它接受坐标X、Y和Z的数据集。

根据我们想要赋予三维图的属性,需要更多的论证。

首次创建Matplotlib时,只考虑二维绘图。大约在1.0版本发布时,通过在Matplotlib的二维显示器上分层一些三维图表工具,创建了一个实用的(尽管相当有限)三维数据可视化工具集。通过导入mplot3d工具包(它是基本Matplotlib安装的一部分),三维图表成为可能。

最简单的三维图是由(x,y,z)三元组的线或簇组成的散点图。这些可以用斧头生产。plot3D和ax。scatter3D函数,很像之前呈现的更典型的二维图表。它们的呼叫特征与二维对应物非常相似。

为了在页面上创建深度错觉,散射点的透明度已经改变。

示例1:

# importing the necessary libraries import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d # generating random dataset z = np.random.randint(80, size =(55)) x = np.random.randint(60, size =(55)) y = np.random.randint(64, size =(55)) # Creating figures for the plot fig = plt.figure(figsize = (10, 7)) ax = plt.axes(projection ="3d") # Creating a plot using the random datasets ax.scatter3D(x, y, z, color = "red") plt.title("3D scatter plot") # display the plot plt.show()

输出:

解释:

在上面的示例中,我们使用ax创建了三维绘图。scatter()函数。我们最初已经导入了所需的所有库,如numpy、matplotlib和mpl_toolkits。然后,我们使用randInt()函数创建了随机数的x、y和z坐标的数据集。在那之后,我们使用了斧头。scatter3D()函数,并输入x、y和z坐标,我们为点取红色。最后,我们使用show()函数显示绘图。

示例2:

# importing the necessary libraries 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(b = True, color ='blue',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()

输出:

解释:

在上面的代码中,我们用函数ax绘制了三维图。scatter3D()函数。我们生成了x、y和z坐标的随机数据集,并使用标记“^”绘制了它们。我们使用set_label函数为各个轴提供标签。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。