Plotting 2 variables with a heat map

流过昼夜 提交于 2019-12-11 00:01:37

问题


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

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


回答1:


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)

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

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

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:


Lets say z = f(x, y). Your heatmap's key is able to represent one dimension only (usually that would be z). What do you mean by

represent the method f(x,y)

For 2-dimensional plotting, you would need a 3-dimensional heatmap.



来源:https://stackoverflow.com/questions/38953668/plotting-2-variables-with-a-heat-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!