Python使用Matplotlib绘制散点趋势线的代码详解
Matplotlib绘制散点趋势线
散点图是一种数据可视化,它使用点来表示两个不同变量的值。水平轴和垂直轴上每个点的位置表示单个数据点的值。散点图用于观察变量之间的关系。
1.创建基本散点图
让我们从创建一个基本的散点图开始。为了简单起见,我们将使用随机数据。
import matplotlib.pyplot as plt import numpy as np x = np.random.rand(50) y = np.random.rand(50) plt.scatter(x, y) plt.title("Basic Scatter Plot") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.show()
2.添加线性趋势线
线性趋势线是最能代表散点图上数据的直线。要添加线性趋势线,我们可以使用NumPy的polyfit()函数来计算最佳拟合线。
# Calculate the best-fit line z = np.polyfit(x, y, 1) p = np.poly1d(z) # Plot the scatter plot and the trend line plt.scatter(x, y) plt.plot(x, p(x), "r--") # 'r--' is for a red dashed line plt.title("Scatter Plot with Linear Trend Line") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.show()
3.添加多项式趋势线
有时,线性趋势线可能不足以捕捉变量之间的关系。在这种情况下,多项式趋势线可能更合适。我们可以使用polyfit()函数,它的阶数更高。
# Calculate the polynomial trend line (degree 2) z = np.polyfit(x, y, 2) p = np.poly1d(z) # Plot the scatter plot and the polynomial trend line plt.scatter(x, y) plt.plot(x, p(x), "g-") # 'g-' is for a green solid line plt.title("Scatter Plot with Polynomial Trend Line") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.show()
自定义趋势线
Matplotlib允许对图进行广泛的自定义,包括趋势线的外观。您可以修改趋势线的颜色、线型和宽度。
# Calculate the best-fit line z = np.polyfit(x, y, 1) p = np.poly1d(z) # Plot the scatter plot and the customized trend line plt.scatter(x, y) plt.plot(x, p(x), color="purple", linewidth=2, linestyle="--") plt.title("Scatter Plot with Customized Trend Line") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.show()
多条趋势线
在某些情况下,您可能希望比较同一散点图上的不同趋势线。这可以通过计算和绘制多条趋势线来实现。
# Generate random data x = np.random.rand(50) y = np.random.rand(50) # Calculate the linear and polynomial trend lines z1 = np.polyfit(x, y, 1) p1 = np.poly1d(z1) z2 = np.polyfit(x, y, 2) p2 = np.poly1d(z2) # Plot the scatter plot and both trend lines plt.scatter(x, y) plt.plot(x, p1(x), "r--", label="Linear Trend Line") plt.plot(x, p2(x), "g-", label="Polynomial Trend Line") plt.title("Scatter Plot with Multiple Trend Lines") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.legend() plt.show()
总结
在Matplotlib中向散点图添加趋势线是可视化和理解变量之间关系的强大方法。无论您需要简单的线性趋势线还是更复杂的多项式趋势线,Matplotlib都提供了创建信息丰富且视觉上吸引人的图表所需的工具。
到此这篇关于Python使用Matplotlib绘制散点趋势线的代码详解的文章就介绍到这了,更多相关Python Matplotlib散点趋势图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python ForMaiR实现自定义规则的邮件自动转发工具
这篇文章主要为大家介绍了python ForMaiR实现自定义规则的邮件自动转发工具示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-12-12Python中的进程操作模块(multiprocess.process)
这篇文章介绍了Python中的进程操作模块(multiprocess.process),文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-05-05
最新评论