matplotlib 如何将多个1D分布式热图绘制为单个图上的条形图?

7z5jn7bk  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(94)

本质上,我试图将多个直方图转换为单个图上的1D热图“条”,如下图所示。


的数据
我不太确定从哪里开始,因为我不太习惯数据可视化,并且只对matplotlib和seaborn有一点了解。
我在做一些事情上取得了一些进展,但这绝对不是我一直在寻找的。

# Define the arrays
foo = np.array([0, 2, 3, 1, 0])
bar = np.array([0, 0, 2, 1, 0])
baz = np.array([0, 1, 1, 0, 0])

# Define the corresponding bin labels
bin_labels = ['0.0-0.2', '0.2-0.4', '0.4-0.6', '0.6-0.8', '0.8-1.0']

# Concatenate the arrays vertically
combined_data = np.vstack((foo, bar, baz))

# Create the histogram plot
# sns.heatmap(combined_data, cmap='YlGnBu', annot=True, fmt='d', xticklabels=bin_labels, cbar=False)
sns.heatmap(combined_data, cmap='Blues', fmt='d', xticklabels=bin_labels, yticklabels=["foo","bar","baz"], cbar=True)
plt.xlabel('Counts')
plt.ylabel('Type')
plt.title('Counts Heatmap')

# Display the plot
plt.show()

字符串


ni65a41a

ni65a41a1#

您可以创建一个matplotlib堆叠条形图,其中每个段的高度相同,但您可以根据百分比更改颜色。

import numpy as np
import matplotlib.pyplot as plt

plt.close("all")

group_names = ["foo", "bar", "baz"]
bin_labels = ["0.0-0.2", "0.2-0.4", "0.4-0.6", "0.6-0.8", "0.8-1.0"]

foo = np.array([0, 2, 3, 1, 0])
bar = np.array([0, 0, 2, 1, 0])
baz = np.array([0, 1, 1, 0, 0])
groups = [foo, bar, baz]

combined = np.vstack(groups)
percentages = combined.T/np.sum(combined, axis=1)

# creates the cmap that is normalized to the observed range
cmap = plt.get_cmap("Blues")
norm = plt.Normalize(np.min(percentages), np.max(percentages))
color = lambda c: cmap(norm(c))

# each bar is the same height and only differs by color
fig, ax = plt.subplots()
for i, p in enumerate(percentages):
    ax.bar(group_names, 1, bottom=i, width=0.5, color=color(p))

ax.set_yticks(ticks=np.arange(0.5, len(bin_labels) + 0.5)) 
ax.set_yticklabels(bin_labels)
fig.colorbar(plt.cm.ScalarMappable(cmap=cmap, norm=norm), ax=ax)
fig.show()

字符串


的数据
如果将edgecolor="lightgray"添加到条形图调用中,可能会更清楚一些,但这取决于您。


相关问题