python - Python中的散点图和颜色映射

标签 python matplotlib

我有一系列点 x 和 y 存储在 numpy 数组中。 它们代表 x(t) 和 y(t),其中 t=0...T-1

我正在绘制散点图

import matplotlib.pyplot as plt

plt.scatter(x,y)
plt.show()

我想要一个表示时间的颜色图(因此根据 numpy 数组中的索引对点进行着色)

最简单的方法是什么?

最佳答案

这是一个例子

import numpy as np
import matplotlib.pyplot as plt

x = np.random.rand(100)
y = np.random.rand(100)
t = np.arange(100)

plt.scatter(x, y, c=t)
plt.show()

这里您根据索引设置颜色,t,它只是一个 [1, 2, ..., 100] 的数组。 enter image description here

也许一个更容易理解的例子是稍微简单一些

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
plt.scatter(x, y, c=t)
plt.show()

enter image description here

请注意,作为 c 传递的数组不需要具有任何特定的顺序或类型,即不需要像这些示例中那样排序或整数。绘图例程将缩放颜色图,使得 c 中的最小/最大值对应于颜色图的底部/顶部。

颜色图

您可以通过添加来更改颜色图

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.cmap_name)

导入 matplotlib.cm 是可选的,因为您也可以将颜色图称为 cmap="cmap_name"。有一个reference page显示每个外观的颜色图。还知道您可以通过简单地将其称为 cmap_name_r 来反转颜色图。所以要么

plt.scatter(x, y, c=t, cmap=cm.cmap_name_r)
# or
plt.scatter(x, y, c=t, cmap="cmap_name_r")

会起作用。例如 "jet_r"cm.plasma_r。以下是新的 1.5 颜色图 viridis 的示例:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(100)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')
plt.show()

enter image description here

颜色条

您可以使用添加颜色条

plt.scatter(x, y, c=t, cmap='viridis')
plt.colorbar()
plt.show()

enter image description here

请注意,如果您明确使用图形和子图(例如 fig, ax = plt.subplots()ax = fig.add_subplot(111)),请添加颜色条可能会涉及更多。可以找到很好的例子here for a single subplot colorbarhere for 2 subplots 1 colorbar .

关于python - Python中的散点图和颜色映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17682216/

相关文章:

python - 收集值后重置字符串数据

python - 从 Python 中查找 Linux 中特定 PID 的命令

python - 使用 python pandas 将现有的 excel 表 append 到新的数据框

python - Pyplot 用轴移动原点

python - 使用 Python 打开到外部计算机的套接字

python - 删除 x 刻度但保留网格线

python - 为什么 matplotlib 颜色条中有一些不必要的线条?

python - 如何随着时间的推移绘制信号的积分?

python - 带阴影线的 matplotlib 自定义图例

python - 在给定条件下替换 Pandas 系列中的值