user3756366
user3756366

Reputation: 37

Matplotlib: How to plot grid boxes colored by number

I have a file with the following data

0018.00 -083.00 45
0018.00 -082.00 55
0018.00 -081.00 15
0019.00 -100.00 25
0019.00 -099.00 45
0019.00 -098.00 05
0019.00 -086.00 25
0019.00 -085.00 25
0019.00 -084.00 35
0019.00 -083.00 45

The first column contains the y values.
The second column contains the x values.
The third column contains the z values.
I would like to assign a color to each z value and plot gridboxes of this dataset.

For instance

05=Brown
15=Red
25=Green
35=Blue
45=Purple
55=Orange

It will look similar to the following image ![enter image description here][1]

I have tried looking at the mathplotlib thumbnails, but they seem to only work with random datasets.

What code should I use to plot my columned data?

So far, I have tried the following code

import numpy
import matplotlib.pyplot as plt

cm = plt.cm.get_cmap('RdYlBu')

var = numpy.loadtxt('map.csv')

y = var[:, 0:1]
x = var[:, 1:2]
colors = var[:, 2:3]

plt.scatter(x, y, colors, cmap=cm)
plt.show()

Upvotes: 1

Views: 1616

Answers (2)

lmjohns3
lmjohns3

Reputation: 7592

While the approach you've shown using scatter does work, it takes a little bit of tweaking to get things to look right. Here's a stab at it:

import numpy as np
import matplotlib.pyplot as plt

# unpack columns from map.csv into x y and z variables.
y, x, z = np.loadtxt('map.csv').T

ax = plt.subplot(111, aspect='equal')
ax.scatter(x, y, c=z, marker='s', s=160, lw=0, cmap='RdYlBu')
plt.show()

Notice that I've played with the marker shape (marker='s') and size (s=160), as well as specified that the z values are to be used as the color (c=z).

However, as you've noticed, scatter isn't designed to show a regular grid like what you're really looking for. You'd be better off going with imshow or one of the pcolor variants like @heltonbiker suggests.

Upvotes: 1

heltonbiker
heltonbiker

Reputation: 27605

You could use imshow

import numpy
import matplotlib.pyplot as plt

content = numpy.loadtxt('map.csv', delimiter=',')

# here you would have to create a "grid"
# where each value in content would be "binned" to the correct position,
# creating the array named "bins"

plt.imshow(bins, 
           interpolation='nearest',
           cmap=plt.cm.RdYlBu,
           extent=[xmin, xmax, ymin, ymax])  ## you should be able to figure these out

Upvotes: 1

Related Questions