Mason
Mason

Reputation: 79

How to create a scatter plot in Python with cbar

I am trying to create a scatter plot with a cbar of my data which I have stored in a .txt file. I found a piece of code here on stackoverflow and tested it to see whether it would work with my data.

The example code is as follows:

for record in range(5):
    x = rand(50)
    y = rand(50)
    c = rand(1)[0] * np.ones(x.shape)
    X.append(x)
    Y.append(y)
    C.append(c)
X = np.hstack(X)
Y = np.hstack(Y)
C = np.hstack(C)
ms=45
s = plt.scatter(X,Y,c=C, cmap=cm,s=ms)
cbar = plt.colorbar()
cbar.set_label('test')
plt.savefig('pics/test/test.png', dpi=300)

The above code produces the following scatter plot:

enter image description here

I have adapted the above simple code into something like this for my data:

cm = plt.cm.get_cmap('YlOrRd')
x, y, z = np.loadtxt('test.txt', unpack=True) 
ms=45
pareto = plt.scatter(x,y,z, cmap=cm,s=ms)
cbar = plt.colorbar()
cbar.set_label('test')
plt.savefig('pics/test/test.png', dpi=300)

However, the above code returns with the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Mason\Desktop\WinPython-64bit-2.7.6.4\python- 
2.7.6.amd64\lib\site- 
packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in 
runfile
    execfile(filename, namespace)
  File "F:/Optimisation/Plotting_data.py", line 28, in 
<module>
    d = plt.scatter(x,y,z, cmap=cm,s=ms)
TypeError: scatter() got multiple values for keyword argument 's'
>>> 

Also, how could I adjust my axis limits?

Upvotes: 3

Views: 1045

Answers (2)

BenT
BenT

Reputation: 3200

You almost had it. You just need to specify that your colors pertain to the z array since scatter plots don't need a 3rd value. Just specify that c=z in your code and your good to go.

cm = plt.cm.get_cmap('YlOrRd')
x, y, z = np.loadtxt('test.txt', unpack=True) 
ms=45
pareto = plt.scatter(x,y,c=z, cmap=cm,s=ms) #change to c=z
cbar = plt.colorbar()
cbar.set_label('test')
plt.savefig('pics/test/test.png', dpi=300)

And as noted by Jacob, use plt.xlim() and plt.ylim() to adjust limits.

Upvotes: 1

Jacob Deasy
Jacob Deasy

Reputation: 336

The scatter function takes in 2 keyword arguments, not the 3 you are passing in within the line:

pareto = plt.scatter(x,y,z, cmap=cm,s=ms)

If you need to plot in 3D dimensions you could look into mplot3d.

To adjust your axis limits you could use:

plt.xlim(x_low, x_high)
plt.ylim(y_low, y_high)

Upvotes: 1

Related Questions