Axblert
Axblert

Reputation: 576

Position colorbar above 2d Histogram (instead of below)

I have a 2d histogram that displays nicely and I want to position the colorbar on top of the Chart, instead of below, where it resides currently.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline
%config InlineBackend.figure_format = 'retina'

fuel_econ = pd.read_csv('./data/fuel_econ.csv')

bins_x = np.arange(0.6, fuel_econ['displ'].max()+0.3, 0.3)
bins_y = np.arange(0, fuel_econ['co2'].max()+40, 40)

plt.hist2d(data = fuel_econ, x = 'displ', y = 'co2', bins = [bins_x, bins_y], 
               cmap = 'plasma_r', cmin = 0.9)

plt.colorbar(orientation='horizontal')
plt.xlabel('Displacement (l)')
plt.ylabel('CO2 (g/mi)')

Histogram

Browsing through the documentation, I couldn't find anything. Thanks for your ideas.

Upvotes: 2

Views: 751

Answers (1)

JohanC
JohanC

Reputation: 80459

The official matplotlib docs have an example using an 'axes divider' to position a colorbar at the top.

Here is your adapted code, together with some random data to get a standalone example:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.colorbar import colorbar

N = 10000
fuel_econ = pd.DataFrame({'displ': np.random.uniform(0.6, 7, N), 'co2': np.zeros(N)})
fuel_econ.co2 = np.random.normal(fuel_econ.displ*100+100, 100)

bins_x = np.arange(0.6, fuel_econ['displ'].max() + 0.3, 0.3)
bins_y = np.arange(0, fuel_econ['co2'].max() + 40, 40)

hist = plt.hist2d(data=fuel_econ, x='displ', y='co2', bins=[bins_x, bins_y],
                  cmap='plasma_r', cmin=0.9)
plt.xlabel('Displacement (l)')
plt.ylabel('CO2 (g/mi)')

ax = plt.gca()
ax_divider = make_axes_locatable(ax)
# define size and padding of axes for colorbar
cax = ax_divider.append_axes('top', size='5%', pad='4%')
# you need to get a mappable obj (get_children)
colorbar(ax.get_children()[0], cax=cax, orientation='horizontal')
# locate colorbar ticks (default is at the botttom)
cax.xaxis.set_ticks_position('top')

plt.show()

example plot

Upvotes: 2

Related Questions