atstack
atstack

Reputation: 163

Plot RGB map from three columns of data using Matplotlib

Is it possible to plot a map of RGB values using Matplotlib?

I have three columns of data that I read from a text file in the following form where x and y are the desired coordinates and z is a hex string of the desired rgb color to plot at the given coordinates:

x   y   z 
1 0.5 #000000
2 0.5 #FF0000
3 0.5 #00FF00
1 1.5 #0000FF
2 1.5 #FFFF00
3 1.5 #00FFFF
1 1.5 #FF00FF
2 2.5 #C0C0C0
3 2.5 #FFFFFF

This is my current state of code. An error is thrown from the griddata() function:

import pandas as pds
import matplotlib.pyplot as plt

# Import text file using pandas
datafile = pds.read_csv(PathToData,sep='\t')

X=datafile.x
Y=datafile.y
Z=datafile.z

# Generate mesh as 'numpy.ndarray' type for plotting
# This throws the following error:
# ValueError: could not convert string to float: #FFAA39
Z=griddata(X, Y, Z, unique(X), unique(Y))

Many thanks

Upvotes: 0

Views: 2664

Answers (1)

tacaswell
tacaswell

Reputation: 87496

griddata is a function for interpolating unevenly spaced data on to a grid (griddata doc). In your case, it looks like you already have data on a grid, you just need to reshape it. The error you are getting arises because griddata is trying to convert you color hex codes to floats for the interpolation, which you should be getting because there is not a sensible float interpertation of #00FF00.

data_dims = (3, 3) # or what ever your data really is
X = np.asarray(x).reshape(data_dims)
Y = np.asarray(y).reshape(data_dims)
C = np.asarray([mpl.colors.colorConverter.to_rgb(_hz) for _hz in z]).reshape(data_dims + (3,)) 
# the colors converted to (r, g, b) tuples

The asarray calls are to make sure we have arrays, not data frames.

If you just want to see the array we can use imshow to plot it:

imshow(c, interpolation='none', 
       origin='bottom', 
       extent=[np.min(X), np.max(X), np.min(Y), np.max(Y)])

color converter doc, imshow doc.

You might need to transpose/flip/rotate C to get the orientation you expect.

Upvotes: 1

Related Questions