Alexis Eggermont
Alexis Eggermont

Reputation: 8165

getting color from 0-1 range in matplotlib

I have a number of scatterplots for which i would the color of the plot to represent correlation between the variables. Correlation is normalized to [0,1] and I would like something like blue for 0 to red for 1, but I'm ok with other combinations.

What is the code to convert my correlation figure to something matplotlib puts on a color spectrum?

for col_s in s_data.columns[1:3]:
    for col_e in economic_data.columns[1:3]:
        x= s_data[col_s].interpolate(method='nearest').tolist()
        y= economic_data[col_e].interpolate(method='nearest').tolist()

        corr=np.corrcoef(x,y)[0,1]
        plt.scatter(x, y, alpha=0.5, c=to_rgb(corr))
        plt.show()

Upvotes: 1

Views: 4330

Answers (2)

adrianus
adrianus

Reputation: 3199

You could map your parameter in [0, 1] to a hex value:

def corr2hex(n):
    ''' Maps a number in [0, 1] to a hex string '''
    if n == 1: return '#fffff'
    else: return '#' + hex(int(n * 16**6))[2:].zfill(6)

print corr2hex(0.31)

>>> 
#4f5c28

Then you can pass this to matplotlibs to_rgb() to get back a RGB triple.

Upvotes: 0

FTA
FTA

Reputation: 345

You can specify a color map and then define the colors simply as the correlations dependent on that color map. First, you need to import cm from matplotlib:

import matplotlib.cm as cm

Then, change your code's plot line to:

plt.scatter(x, y, alpha=0.5, c=corr, cmap=cm.rainbow)

You are able to customize the color map with any of matplotlib's color maps.

Upvotes: 3

Related Questions