Matplotlib:如何使imshow从其他numpy数组中读取x,y坐标? [英] Matplotlib: how to make imshow read x,y coordinates from other numpy arrays?

查看:173
本文介绍了Matplotlib:如何使imshow从其他numpy数组中读取x,y坐标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您想用imshow绘制一个numpy数组时,通常会这样做:

When you want to plot a numpy array with imshow, this is what you normally do:

import numpy as np
import matplotlib.pyplot as plt

A=np.array([[3,2,5],[8,1,2],[6,6,7],[3,5,1]]) #The array to plot

im=plt.imshow(A,origin="upper",interpolation="nearest",cmap=plt.cm.gray_r)
plt.colorbar(im)

这给了我们这个简单的图像:

Which gives us this simple image:

在此图像中,只需从数组中每个值的位置提取 x y 坐标.现在,假设A是一个值数组,这些值引用某些特定的坐标:

In this image, the x and y coordinates are simply extracted from the position of each value in the array. Now, let's say that A is an array of values that refer to some specific coordinates:

real_x=np.array([[15,16,17],[15,16,17],[15,16,17],[15,16,17]])
real_y=np.array([[20,21,22,23],[20,21,22,23],[20,21,22,23]])

这些值是根据我的情况而编造的. 是否可以强制imshow为A中的每个值分配对应的一对坐标(real_x,real_y)?

These values are made-up to just make my case. Is there a way to force imshow to assign each value in A the corresponding pair of coordinates (real_x,real_y)?

PS:我不是要在基于数组的x和y中添加或减去某些东西,以使其与 real_x real_y 匹配,但对于从 real_x real_y 数组读取的这些值.然后,预期的结果是在x轴上具有 real_x 值且在y轴上具有 real_y 值的图像.

PS: I am not looking for adding or subtracting something to the array-based x and y to make them match real_x and real_y, but for something that reads these values from the real_x and real_y arrays. The intended outcome is then an image with the real_x values on the x-axis and the real_y values on the y-axis.

推荐答案

设置范围

假设您有

real_x=np.array([15,16,17])
real_y=np.array([20,21,22,23])

您将图像范围设置为

dx = (real_x[1]-real_x[0])/2.
dy = (real_y[1]-real_y[0])/2.
extent = [real_x[0]-dx, real_x[-1]+dx, real_y[0]-dy, real_y[-1]+dy]
plt.imshow(data, extent=extent)

更改刻度标签

另一种选择是只更改刻度标签

Changing ticklabels

An alternative would be to just change the ticklabels

real_x=np.array([15,16,17])
real_y=np.array([20,21,22,23])
plt.imshow(data)
plt.gca().set_xticks(range(len(real_x)))
plt.gca().set_yticks(range(len(real_x)))
plt.gca().set_xticklabels(real_x)
plt.gca().set_yticklabels(real_y)

这篇关于Matplotlib:如何使imshow从其他numpy数组中读取x,y坐标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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