import matplotlib.pyplot as plt
import numpy as np
vmin, vmax = 0, 10
# By default data is plot in the order given
sizes1 = (10, 50, 100)
data1 = [np.random.randint(vmin, vmax, s) for s in sizes1]
labels1 = [f"Size: {len(x)}" for x in data1]
# You can sort the data the way you want
data2 = sorted(data1, key=lambda x: -len(x))
labels2 = [f"Size: {len(x)}" for x in data2]
sizes2 = tuple(len(x) for x in data2)
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.hist(data1, stacked=True, rwidth=0.5, label=labels1)
ax1.set_title(sizes1)
ax1.legend()
ax2.hist(data2, stacked=True, rwidth=0.5, label=labels2)
ax2.set_title(sizes2)
ax2.legend()
plt.show()
bins = np.arange(vmin, vmax + 1)
x = bins[:-1] + 0.5
ys = [np.histogram(data, bins=bins)[0] for data in data2]
fig, ax = plt.subplots()
bottom = np.zeros_like(ys[0])
for y, label in zip(ys, labels2):
ax.bar(x, y, bottom=bottom, label=label)
bottom += y
ax.legend()
plt.show()
1条答案
按热度按时间qyyhg6bp1#
默认情况下,组按照
hist
函数给定的顺序从下到上绘制。因此,您可以根据需要对序列进行排序,例如按每个组的大小的相反顺序:
字符串
的数据
**编辑:**使用
ax.bar
。仍然是同样的想法,对数据进行充分排序并按该顺序绘制,但在这里您对绘制顺序负有全部责任。
因此,取已经排序的
data2
,我们有:型
的