亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python使用Matplotlib繪制散點趨勢線的代碼詳解

 更新時間:2025年01月08日 09:31:33   作者:python收藏家  
Matplotlib是一個用于數(shù)據(jù)可視化的強大Python庫,其基本功能之一是創(chuàng)建帶有趨勢線的散點圖,散點圖對于可視化變量之間的關(guān)系非常有用,本文將指導(dǎo)您使用Matplotlib繪制散點趨勢線的過程,涵蓋線性和多項式趨勢線,需要的朋友可以參考下

Matplotlib繪制散點趨勢線

散點圖是一種數(shù)據(jù)可視化,它使用點來表示兩個不同變量的值。水平軸和垂直軸上每個點的位置表示單個數(shù)據(jù)點的值。散點圖用于觀察變量之間的關(guān)系。

1.創(chuàng)建基本散點圖

讓我們從創(chuàng)建一個基本的散點圖開始。為了簡單起見,我們將使用隨機數(shù)據(jù)。

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.添加線性趨勢線

線性趨勢線是最能代表散點圖上數(shù)據(jù)的直線。要添加線性趨勢線,我們可以使用NumPy的polyfit()函數(shù)來計算最佳擬合線。

# 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.添加多項式趨勢線

有時,線性趨勢線可能不足以捕捉變量之間的關(guān)系。在這種情況下,多項式趨勢線可能更合適。我們可以使用polyfit()函數(shù),它的階數(shù)更高。

# 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()

多條趨勢線

在某些情況下,您可能希望比較同一散點圖上的不同趨勢線。這可以通過計算和繪制多條趨勢線來實現(xiàn)。

# 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()

總結(jié)

在Matplotlib中向散點圖添加趨勢線是可視化和理解變量之間關(guān)系的強大方法。無論您需要簡單的線性趨勢線還是更復(fù)雜的多項式趨勢線,Matplotlib都提供了創(chuàng)建信息豐富且視覺上吸引人的圖表所需的工具。

到此這篇關(guān)于Python使用Matplotlib繪制散點趨勢線的代碼詳解的文章就介紹到這了,更多相關(guān)Python Matplotlib散點趨勢圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論