用热图绘制2个变量 [英] Plotting 2 variables with a heat map

查看:220
本文介绍了用热图绘制2个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 3上,我有两个变量x和y,其中x的范围是1到5,y的范围是0.03到0.7,然后我有一个采用x和y并生成标量数的方法.我想创建一个热图类型图,其中x为x轴,y为y轴,并使用一个颜色键来表示方法f(x,y).这是怎么做的?我尝试使用热图,但是由于范围无法获得一致的x和y范围,因此罐头似乎可以正常使用.这是我找到的示例,与我正在寻找的示例很接近

I'm on the python 3 and I have two variables x and y, where x ranges from 1 to 5 and y from 0.03 to 0.7 and I then have a method that takes x and y and generates a scalar number. I want to create a heat map type plot with x as the x-axis and y as the y axis and a colour key to represent the method f(x,y). How is this done? I've tried using heatmaps but cans seem to get it to work due to ranges not being able to get agreeable ranges of x and y. Here's an example I found and that is close to what I'm looking for

import numpy as np
import numpy.random
import matplotlib.pyplot as plt


x = np.random.randn(8873)
y = np.random.randn(8873)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap, extent=extent)
plt.show()

但是我希望颜色用键来表示f(x,y)

But I want the colour to represent f(x,y) with a key

推荐答案

如果从2个一维向量开始,则xy在一个网格上计算xy的函数首先必须使用numpy.meshgrid生成2D点.

If you start with 2 mono-dimensional vectors, x and y to compute a function of x and y on a grid of 2D points you have first to generate said 2D grid, using numpy.meshgrid.

from numpy import linspace, meshgrid
x, y = linspace(1, 5, 41), linspace(0.03, 0.70, 68)
X, Y = meshgrid(x, y)

看到两个网格有点令人惊讶...一个仅包含x值,另一个仅包含y值(您只需打印XY亲自查看).

It's somehow a surprise to see that you get two grids... one contains only the x values and the other only the y values (you have just to print X and Y to see for yourself).

有了这两个网格,您可以计算结果网格,但这仅在使用numpyufuncs ...例如

With these two grids available, you can compute a grid of results, but this works only when you use numpy's ufuncs... e.g.

def f(x, y):
    from numpy import sin, sqrt
    return sin(sqrt(x*x+y*y))

并最终可以绘制结果,您要使用的pyplot方法是pcolor,并且要添加必须使用的色条(通常是pyplot),请使用colorbar方法...

and eventually you can plot your results, the pyplot method that you want to use is pcolor, and to add a colorbar you have to use, always from pyplot, the colorbar method...

from matplotlib.pyplot import colorbar, pcolor, show
Z = f(X, Y)
pcolor(X, Y, Z)
colorbar()
show()

当最终达到这一点时,传统要求输出样本 就这样

When this point is eventually reached, tradition asks for a sample output That's all

这篇关于用热图绘制2个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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