如何在 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.