6

I try to do a scatterplot of lll and bbb variables with amplitudes as color with a mollweide projection with a colorbar.

If I do

import pylab as plt
import numpy as np
lll=N.random.uniform(-180,180,10000)
bbb=N.random.uniform(-90,90,10000)
amp=N.random.uniform(0,1,10000)

fig = plt.figure(figsize=(12,9))
ax = fig.add_subplot(111, projection="mollweide")
ax.scatter(N.array(lll)*N.pi/180., N.array(bbb)*N.pi/180., c=amp)

ax.grid(True)

I get the plot I want but without the colorbar. If I add a line with ax.colorbar() or plt.colorbar() it don't work.

Thanks in advance for your help.

AlbertBranson
  • 405
  • 2
  • 7
  • 1
    Welcome to SO. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and edit your question accordingly. – Mr. T May 16 '18 at 09:00
  • Possible duplicate of [matplotlib colorbar for scatter](https://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter) – DavidG May 16 '18 at 09:12
  • Thanks, I edit to get a minimal working code. Its not a duplicate of https://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter , I use mollweide projection – AlbertBranson May 16 '18 at 09:14
  • Did you try the solution in the duplicate? For me it produces a colorbar – DavidG May 16 '18 at 09:15
  • yes, I a add plt.colorbar(ax), I get AttributeError: 'MollweideAxesSubplot' object has no attribute 'autoscale_None' – AlbertBranson May 16 '18 at 09:17

1 Answers1

5

You need to return the value from ax.scatter, then pass that as an argument into plt.colorbar (not the axes itself):

lll=np.random.uniform(0,360,10000)
bbb=np.random.uniform(-90,90,10000)
amplitudes=np.random.uniform(0,1,10000)

l_axis_name ='latitude l (deg)'
b_axis_name = 'longitude b (deg)'

for i in range(len(lll)):
    if lll[i]>180:
        lll[i] -= 360
fig = plt.figure(figsize=(12,9))
ax = fig.add_subplot(111, projection="mollweide")
ax.grid(True)

sc = ax.scatter(np.array(lll)*np.pi/180., np.array(bbb)*np.pi/180., c=amplitudes)
plt.colorbar(sc)

plt.show()

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82