Matplotlib - 反轉座標軸



什麼是反轉座標軸?

在 Matplotlib 中,反轉座標軸是指改變座標軸的方向,將其從預設方向翻轉。此操作透過反轉特定座標軸(通常是 x 軸或 y 軸)上的資料順序來更改繪圖的視覺化表示。

反轉 X 軸

要在 Matplotlib 中反轉 x 軸,可以使用 `plt.gca().invert_xaxis()` 函式。此方法反轉 x 軸的方向,有效地將繪圖水平翻轉。最初從左到右繪製的資料點現在將從右到左顯示。

以下是關於如何反轉 x 軸的詳細分解

反轉 X 軸的步驟

以下是反轉 x 軸的步驟。

建立繪圖

使用 Matplotlib 使用我們的資料生成繪圖。

示例

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot with default axis orientation
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Default X-axis')
plt.show()
輸出
Creating XPLT

反轉 X 軸

建立繪圖後,使用 `plt.gca().invert_xaxis()` 反轉 x 軸。

示例

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot with default axis orientation
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Default X-axis')
plt.show()

# Reversing the x-axis
plt.plot(x, y, marker='o')
plt.gca().invert_xaxis()  # Reverse x-axis
plt.xlabel('Reversed X-axis')
plt.ylabel('Y-axis')
plt.title('Reversed X-axis')
plt.show()
輸出
Creating XPLT Reverse Plot

第二個繪圖將顯示與第一個繪圖相同的資料,但 x 軸將被反轉。最初位於左側的資料點現在將透過更改資料的視覺化表示出現在右側。

反轉 X 軸的用例

翻轉時間序列資料 - 當我們繪製時間序列資料時,反轉 x 軸可能更符合時間順序。

重新定向地理繪圖 - 在某些地理繪圖中,反轉 x 軸可能符合預期的方向或約定。

反轉 x 軸提供了視覺化資料的另一種視角,使我們能夠以不同的順序或方向呈現資訊,以便更清晰地瞭解或更好地符合約定。

此函式透過水平翻轉繪圖來反轉 x 軸的方向。最初從左到右繪製的資料點現在將從右到左顯示。

反轉 Y 軸

`plt.gca().invert_yaxis()` 函式透過垂直翻轉繪圖來反轉 y 軸的方向。最初從下到上繪製的資料點現在將從上到下顯示。

Y 軸的反轉與我們在上一節中看到的繪圖的 X 軸反轉相同。以下是反轉 Y 軸的步驟。

建立繪圖

使用 Matplotlib 使用我們的資料生成繪圖。

示例
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot with default axis orientation
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Default Y-axis')
plt.show()
輸出
Creating Y-axis

反轉 Y 軸

建立繪圖後,使用 `plt.gca().invert_yaxis()` 反轉 y 軸。

示例
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot with default axis orientation
plt.plot(x, y, marker='o')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Default Y-axis')
plt.show()

# Reversing the x-axis
# Reversing the y-axis
plt.plot(x, y, marker='o')
plt.gca().invert_yaxis()  # Reverse y-axis
plt.xlabel('X-axis')
plt.ylabel('Reversed Y-axis')
plt.title('Reversed Y-axis')
plt.show()
輸出
Creating Y-axis Reverse Yplot
廣告