Python中的散点图和颜色映射 [英] Scatter plot and Color mapping in Python

查看:99
本文介绍了Python中的散点图和颜色映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a range of points x and y stored in numpy arrays. Those represent x(t) and y(t) where t=0...T-1

我正在使用绘制散点图

import matplotlib.pyplot as plt

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

我想要一个代表时间的色图(因此根据numpy数组中的索引为点着色)

I would like to have a colormap representing the time (therefore coloring the points depending on the index in the numpy arrays)

最简单的方法是什么?

推荐答案

以下是示例

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]的数组.

Here you are setting the color based on the index, t, which is just an array of [1, 2, ..., 100].

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

Perhaps an easier-to-understand example is the slightly simpler

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()

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

Note that the array you pass as c doesn't need to have any particular order or type, i.e. it doesn't need to be sorted or integers as in these examples. The plotting routine will scale the colormap such that the minimum/maximum values in c correspond to the bottom/top of the colormap.

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

You can change the colormap by adding

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

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

Importing matplotlib.cm is optional as you can call colormaps as cmap="cmap_name" just as well. There is a reference page of colormaps showing what each looks like. Also know that you can reverse a colormap by simply calling it as cmap_name_r. So either

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的示例:

will work. Examples are "jet_r" or cm.plasma_r. Here's an example with the new 1.5 colormap 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()

您可以通过使用添加颜色条

You can add a colorbar by using

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

请注意,如果您明确使用图形和子图形(例如fig, ax = plt.subplots()ax = fig.add_subplot(111)),则添加色条可能会涉及更多.可以在此处为单个子图颜色栏此处为2个子图1个色条.

Note that if you are using figures and subplots explicitly (e.g. fig, ax = plt.subplots() or ax = fig.add_subplot(111)), adding a colorbar can be a bit more involved. Good examples can be found here for a single subplot colorbar and here for 2 subplots 1 colorbar.

这篇关于Python中的散点图和颜色映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆