4

I am trying to produce a figure like the following in python:

enter image description here

I am done with most part of it and currently based on what I want it looks like this:

enter image description here

And my code is:

plt.scatter(x,y,marker="h",s=100,c=color)
plt.xscale('log')
plt.yscale('log')
plt.xlim([1, 10**3])
plt.ylim([1, 10**3])
plt.colorbar()
plt.show()

Is there any way to make the current colorbar look like the one on top? So to make it smaller and add axis to it?

Any help would be much appreciated.

1

1 Answer 1

8

The key here is the cax kwarg to colorbar. You'll need to create an inset axes, and then use that axes for the colorbar.

As an example:

import numpy as np
import matplotlib.pyplot as plt

npoints = 1000
x, y = np.random.normal(10, 2, (2, npoints))

fig, ax = plt.subplots()
artist = ax.hexbin(x, y, gridsize=20, cmap='gray_r', edgecolor='white')

# Create the inset axes and use it for the colorbar.
cax = fig.add_axes([0.8, 0.15, 0.05, 0.3])
cbar = fig.colorbar(artist, cax=cax)

plt.show()

enter image description here

If you wanted to get fancy and more precisely match things (Note: I'm using hexbin here, which doesn't support log axes, so I'm leaving that part out.)

import numpy as np
import matplotlib.pyplot as plt

npoints = 1000
x, y = np.random.normal(10, 2, (2, npoints))

fig, ax = plt.subplots()
artist = ax.hexbin(x, y, gridsize=20, cmap='gray_r', edgecolor='white')

cax = fig.add_axes([0.8, 0.15, 0.05, 0.3])
cbar = fig.colorbar(artist, cax=cax)

ax.spines['right'].set(visible=False)
ax.spines['top'].set(visible=False)
ax.tick_params(top=False, right=False)

cbar.set_ticks([5, 10, 15])
cbar.ax.set_title('Bin Counts', ha='left', x=0)
cbar.ax.tick_params(axis='y', color='white', left=True, right=True,
                    length=5, width=1.5)
cbar.outline.remove()

plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer, thanks. Any idea how I can get the same thing for log-log chart? My results look much better using a loglog figure and that's why I have to stick to it.
Note: You can set the following options to hexbin : xscale = 'log', yscale = 'log' if you want to use log10 axes
@tom I actually ended up using the x and y scale. Thanks for the comment though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.