如何创建一个直方图,其中每个条都是对应箱子的热图?

2024-09-28 21:09:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

df.head()[['price', 'volumen']]

    price   volumen
48  45      3
49  48      1
50  100     2
51  45      1
52  56      1

它表示具有特定价格的对象的数量。 我基于volume列创建了一个直方图:

enter image description here

我想补充关于每个箱子价格分布的信息。我的想法是使用热图而不是单色列。红色表示高价,黄色表示低价

下面是一个示例图来说明总体思路:

enter image description here


Tags: 数据对象信息df数量价格直方图price
2条回答

您可以使用Seaborn生成热图。首先对数据框进行装箱/整形。这是随机数据,所以热图不是很有趣

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

s = 50
df = pd.DataFrame({"price":np.random.randint(30,120, s),"volume":np.random.randint(1,5, s)})

fig, ax = plt.subplots(2, figsize=[10,6])

df.loc[:,"volume"].plot(ax=ax[0], kind="hist", bins=3)
# reshape for a heatmap... put price into bins and make 2D
dfh = df.assign(pbin=pd.qcut(df.price,5)).groupby(["pbin","volume"]).mean().unstack(1).droplevel(0,axis=1)
axh = sns.heatmap(dfh, ax=ax[1])

enter image description here

以下示例使用seaborn的tips数据集。直方图是通过将total_bill分组到存储箱中创建的。然后,根据每组中的提示对条进行着色

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
import seaborn as sns

sns.set_theme(style='white')
tips = sns.load_dataset('tips')
tips['bin'] = pd.cut(tips['total_bill'], 10)  # histogram bin

grouped = tips.groupby('bin')

min_tip = tips['tip'].min()
max_tip = tips['tip'].max()
cmap = 'RdYlGn_r'
fig, ax = plt.subplots(figsize=(12, 4))
for bin, binned_df in grouped:
    bin_height = len(binned_df)
    binned_tips = np.sort(binned_df['tip']).reshape(-1, 1)
    ax.imshow(binned_tips, cmap=cmap, vmin=min_tip, vmax=max_tip, extent=[bin.left, bin.right, 0, bin_height],
              origin='lower', aspect='auto')
    ax.add_patch(mpatches.Rectangle((bin.left, 0), bin.length, bin_height, fc='none', ec='k', lw=1))

ax.autoscale()
ax.set_ylim(0, 1.05 * ax.get_ylim()[1])
ax.set_xlabel('total bill')
ax.set_ylabel('frequency')
plt.colorbar(ax.images[0], ax=ax, label='tip')
plt.tight_layout()
plt.show()

resulting plot

下面是带状彩色贴图(cmap = plt.get_cmap('Spectral', 9))的外观:

banded colormap

下面是另一个使用'mpg'数据集的示例,该数据集具有汽车重量的直方图和每加仑英里数的颜色

mpg example

相关问题 更多 >