Matplotlib - 網格



在一般的資料視覺化和繪圖中,網格指的是繪圖區域上的一組水平和垂直線。網格線有助於更好地理解圖表上的資料。通常,這些線與 x 軸和 y 軸上的主要刻度線對齊。它們可以增強圖表的可讀性,並更容易估計值。

請參見下面的參考圖片:

Grids Input

主要有兩種型別的網格線:

  • 主要網格線 - 這些是與座標軸上的主要刻度線對齊的主要網格線。

  • 次要網格線 - 這些是主要網格線之間的附加網格線,與座標軸上的次要刻度線對齊。

Matplotlib 中網格的介紹

在 Matplotlib 中啟用網格線是一個簡單的過程。pyplot.grid() 方法向繪圖新增主要網格線,並提供額外的自定義選項,包括調整線型、線寬、顏色和透明度。

讓我們探索向繪圖新增網格線的不同方法。

帶有網格線的基本繪圖

在 Matplotlib 中,預設網格是一組與 x 軸和 y 軸上的主要刻度線對齊的主要網格線。

示例

在這個示例中,我們建立一個基本的正弦波圖並新增預設網格。

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

# create a plot
fig, ax = plt.subplots(figsize=(7,4))

# Plot the data
plt.plot(x, y)

# Add grid
ax.grid(True)

# set the title
ax.set_title('Basic Plot with Grids')

# Show the plot
plt.show()

輸出

執行上述程式碼後,我們將得到以下輸出:

Gridlines Example 1

自定義網格

自定義網格線包括線型、線寬、顏色和透明度。

示例

此示例演示如何透過更改網格線的線型、線寬、顏色和透明度來自定義網格線。

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.arange(0, 1, 0.05)
y = x**2

# Create the plot
fig, ax = plt.subplots(figsize=(7,4))

# Plot the data
plt.scatter(x, y)

# Customize grid
ax.grid(True, linestyle='-.', linewidth=1, color='red', alpha=0.9)

# set the title
ax.set_title('Customizing Grids')

# Show the plot
plt.show()

輸出

執行上述程式碼後,我們將得到以下輸出:

Gridlines Example 2

新增次要網格線

除了主要網格線外,Matplotlib 還支援包含次要網格線。這些線位於主要網格線之間,並與 x 軸和 y 軸上的次要刻度線對齊。您可以使用pyplot.minorticks_on()plt.grid(which='minor') 來新增與次要刻度線對應的網格線。

示例

此示例演示如何向繪圖新增主要和次要網格線。

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.arange(0, 1, 0.05)
y = x**2

# Create the plot
fig, ax = plt.subplots(figsize=(7,4))

# Plot the data
plt.scatter(x, y)

# Add major grid
ax.grid(True)

# Add minor grid
ax.minorticks_on()
ax.grid(which='minor', linestyle=':', linewidth=0.5, color='red', alpha=0.5)

# set the title
ax.set_title('Major and Minor Gridlines')

# Show the plot
plt.show()

輸出

執行上述程式碼後,我們將得到以下輸出:

Gridlines Example 3

手動新增網格

此方法涉及顯式指定垂直線和水平線的位置。透過迭代特定的區間或值,使用者可以在所需位置繪製網格線。這涉及使用諸如pyplot.axvline()pyplot.axhline() 等函式分別繪製垂直線和水平線。

示例

這是一個手動在 x 軸上每三個點繪製垂直網格線的示例。

import matplotlib.pyplot as plt
import numpy as np

# Create some data
x = np.arange(0, 1, 0.05)
y = x**2

# Create the plot
plt.subplots(figsize=(7,4))

# Plot the data
plt.scatter(x, y)

# Set x and y tick locations
plt.xticks(np.arange(0, 1.01, 0.1))
plt.yticks(np.arange(0, 1.01, 0.1))
plt.title('Manually Drawing the Grids ')

# Draw grid lines for every third point on the x-axis
for pt in np.arange(0, 1.01, 0.3):
   plt.axvline(pt, lw=0.5, color='black', alpha=0.5)

# Show the plot
plt.show()

輸出

執行上述程式碼後,我們將得到以下輸出:

Gridlines Example 4

隱藏網格線

可以透過為grid() 函式指定布林值False 來隱藏或刪除繪圖中的網格線。

示例

這是一個隱藏繪圖的網格線和座標軸(X 軸和 Y 軸)的示例。

import numpy as np
import matplotlib.pyplot as plt

#  Create a figure
fig = plt.figure(figsize=(7, 4))

# Generate data
x = np.linspace(-10, 10, 50)
y = np.sin(x)

# Plot horizontal line
plt.axhline(y=0, c="green", linestyle="dashdot", label="y=0")

# Plot sine curve
plt.plot(x, y, c="red", lw=5, linestyle="dashdot", label="y=sin(x)")

# Hide gridlines
plt.grid(False)

# Hide axes
plt.axis('off')

# Add legend
plt.legend()

# Show plot
plt.show()

輸出

執行上述程式碼後,您將得到以下輸出:

Gridlines Example 5

跨越子圖的網格線

在比較多個子圖中的資料時,在所有子圖中使用網格線有助於保持繪圖之間的視覺比較。

示例

此示例演示如何在子圖中繪製網格線。

import matplotlib.pyplot as plt

# Data
d = [1, 2, 3, 4, 5, 6, 7, 8, 9]
f = [0, 1, 0, 0, 1, 0, 1, 1, 0]

# Create figure and subplots
fig = plt.figure(figsize=(7,4))
fig.set_size_inches(30, 10)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Plot data on subplots
ax1.plot(d, marker='.', color='b', label="1 row")

# Draw grid lines behind bar graph
ax2.bar(range(len(d)), d, color='red', alpha=0.5)

# Enable grids on both subplots
ax1.grid()
ax2.grid()

# Display the plot
plt.show()

輸出

執行上述程式碼後,您將得到以下輸出:

Gridlines Example 6
廣告