使用特定列绘制二维NumPy数组 [英] Plot 2-dimensional NumPy array using specific columns

查看:91
本文介绍了使用特定列绘制二维NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样创建的2D numpy数组:

I have a 2D numpy array that's created like this:

data = np.empty((number_of_elements, 7))

每行具有7个(或任何其他)浮点数的值表示对象的属性.例如,前两个是对象的xy位置,其他两个是各种属性,甚至可以用来将颜色信息应用于绘图.

Each row with 7 (or whatever) floats represents an object's properties. The first two for example are the x and y position of the object, the others are various properties that could even be used to apply color information to the plot.

我想从data做一个散点图,所以如果p = data[i],则将一个对象绘制为一个点,并以p[:2]作为其2D位置,并以p[2:4]作为颜色信息(长度的向量应确定该点的颜色).其他列与该图无关紧要.

I want to do a scatter plot from data, so that if p = data[i], an object is plotted as a point with p[:2] as its 2D position and with say p[2:4] as a color information (the length of that vector should determine a color for the point). Other columns should not matter to the plot at all.

我应该怎么做?

推荐答案

设置基本的matplotlib图形很容易:

Setting up a basic matplotlib figure is easy:

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

选择xycolor的列可能看起来像这样:

Picking off the columns for x, y and color might look something like this:

N = 100
data = np.random.random((N, 7))
x = data[:,0]
y = data[:,1]
points = data[:,2:4]
# color is the length of each vector in `points`
color = np.sqrt((points**2).sum(axis = 1))/np.sqrt(2.0)
rgb = plt.get_cmap('jet')(color)

最后一行检索jet色彩图,并将数组color中的每个float值(0和1之间)映射为3元组RGB值. 在此处中有一个可供选择的颜色图列表.还有一种定义自定义颜色图的方法.

The last line retrieves the jet colormap and maps each of the float values (between 0 and 1) in the array color to a 3-tuple RGB value. There is a list of colormaps to choose from here. There is also a way to define custom colormaps.

制作散点图现在很简单:

Making a scatter plot is now straight-forward:

ax.scatter(x, y, color = rgb)
plt.show()
# plt.savefig('/tmp/out.png')    # to save the figure to a file

这篇关于使用特定列绘制二维NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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