2d直方图上方的位置颜色条(而不是下方)

问题描述 投票:1回答:1

我有一个2d直方图,可以很好地显示,我想将颜色条放置在图表的顶部,而不是当前所在的下方。

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

浏览文档,我找不到任何东西。感谢您的想法。

python matplotlib
1个回答
1
投票

官方matplotlib文档有一个示例,该示例使用'axes divider'将颜色栏置于顶部。

这是您改编的代码,以及一些随机数据,以得到一个独立的示例:

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

© www.soinside.com 2019 - 2024. All rights reserved.