1

I have a dataset generated in this way:

 aa = linspace(A - 5, A + 5, n_points)
 bb = linspace(B - 1.5, B + 1.5, n_points)
 z = []
 for a in aa:
     for b in bb:
         z.append(cost([a, b]))

I would like and head map where z define the color in the point (a,b) . I need this to analyze local minimum.

I am using matplotlib but I do not know exactly how to proceed.

Donbeo
  • 17,067
  • 37
  • 114
  • 188
  • Have you tried searching Google or SO? http://matplotlib.org/examples/pylab_examples/hist2d_log_demo.html and https://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor and https://stackoverflow.com/questions/2369492/generate-a-heatmap-in-matplotlib-using-a-scatter-data-set for example – Cory Kramer Mar 28 '14 at 12:04

2 Answers2

5

Typically you'd use imshow or pcolormesh for this.

For example:

import numpy as np
import matplotlib.pyplot as plt

n_points = 10
aa = np.linspace(-5, 5, n_points)
bb = np.linspace(-1.5, 1.5, n_points)

def cost(a, b):
    return a + b

z = []
for a in aa:
    for b in bb:
        z.append(cost(a, b))

z = np.reshape(z, [len(aa), len(bb)])

fig, ax = plt.subplots()
im = ax.pcolormesh(aa, bb, z)
fig.colorbar(im)

ax.axis('tight')
plt.show()

enter image description here

However, it would be better to write your example code as:

import numpy as np
import matplotlib.pyplot as plt

n_points = 10
a = np.linspace(-5, 5, n_points)
b = np.linspace(-1.5, 1.5, n_points)
a, b = np.meshgrid(b, a)

z = a + b # Vectorize your cost function

fig, ax = plt.subplots()
im = ax.pcolormesh(a, b, z)
fig.colorbar(im)

ax.axis('tight')
plt.show()

Or, even more compactly:

import numpy as np
import matplotlib.pyplot as plt

npoints = 10
b, a = np.mgrid[-5:5:npoints*1j, -1.5:1.5:npoints*1j]

z = a + b

fig, ax = plt.subplots()
im = ax.pcolormesh(a, b, z)
fig.colorbar(im)

ax.axis('tight')
plt.show()
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • @Jeo I have a doubt here. If i do not know the a and b coordinates which i have to pull from data file itself, in that case how do we give ? Suppose i have to data set with gps co ordinates of distributed city. –  Mar 17 '15 at 07:28
  • Why is ax.axis('tight') necessary? Thanks :) – tommy.carstensen Dec 15 '15 at 14:37
  • @tommy.carstensen - By default, matplotlib will choose "even" numbers for the axes limits. (Note: this will change to `margins` style padding in 2.0.) `ax.axis('tight')` specifies that the axes limits should exactly match the data limits. In this case, we're not wanting to display regions where we don't have data, so we use `ax.axis('tight')`. – Joe Kington Dec 15 '15 at 14:52
-1

I just did something similar, and I used a Scatter plot.

plt.scatter(x_vals, y_vals, s = 100,  c = z_vals, cmap = 'rainbow')
c = plt.colorbar()
mauve
  • 2,707
  • 1
  • 20
  • 34