如何在 matplotlib 中將顏色條位置向右移動?


要將 matplotlib 中的顏色條位置向右移動,我們可以採取以下步驟 −

步驟

  • 匯入 numpy 和 matplotlib 庫。

  • 設定 figure 的大小並調整子圖之間和周圍的空白。

  • 初始化一個變數 N 來儲存樣本資料的數量。

  • 使用 numpy 建立 xy 資料點。

  • 使用帶有 xy 資料點的 scatter() 方法建立散點圖。

  • 將顏色條新增到圖中,對水平向右或左移動使用 pad 引數。

  • 使用 show() 方法顯示 figure。

示例

# Import numpy and matplotlib
import numpy as np
from matplotlib import pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 100

# Create x and y data points
x = np.random.rand(N)
y = np.random.rand(N)

# Scatter plot with x and y data points
s = plt.scatter(x, y, c=x, cmap='hot', marker='*')

# Add a colorbar with pad value
plt.colorbar(s, shrink=0.9, pad=0.1)

# Display the plot
plt.show()

輸出

它將輸出以下內容 −

如果希望將顏色條設定在左邊,那麼使用 location 引數,如下所示 −

plt.colorbar(s, shrink=0.9, pad=0.1, location="left")

在程式碼中加上這行,輸出將如下所示 −

更新日期: 2022 年 2 月 1 日

2000+ 瀏覽量

啟動您的 職業

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.