Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scatter plot of 2 variables with colorbar based on third variable [duplicate]

I am trying to plot with variable x with respect to another y and add a colormap based on the values of another variable z

So the plot should be similar to this

Plots

My try

import numpy as np
import pandas as pd
import seaborn as sns
import random
import matplotlib.pyplot as plt
import matplotlib.cm as cm

x=np.random.randint(0,20,30)
y=np.random.randint(-5,5,30)
z=np.random.randint(-2,10,30)
df=pd.DataFrame(data={'A':x,'B':y,'C':z})

points = plt.scatter(df['A'],df['B'],cmap="jet")
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array(df['C'])
plt.colorbar(points)
sns.lmplot('A', 'B', data=df, hue='C', fit_reg=False)

TypeError: You must first set_array for mappable

I am mixing matplotlib and seaborn as in seaborn I can not use the colormap 'jet' But any alternative aproaches to get the same graph are welcome

like image 788
gis20 Avatar asked Sep 12 '25 18:09

gis20


1 Answers

How about this (use c=df.C in the scatter command):

points = plt.scatter(df.A, df.B, c=df.C,cmap="jet", lw=0)
plt.colorbar(points)

enter image description here

like image 83
screenpaver Avatar answered Sep 15 '25 09:09

screenpaver