无forloop的条形图

2024-03-28 09:04:10 发布

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

有没有可能摆脱这种循环?你知道吗

这是我的输入数据

import matplotlib.pyplot as plt

frac = [0.75, 0.6093, 0.7025, 0.0437, 0.1]

plt.figure()
orange, blue = '#fd7f28', '#2678b2'

那么这个丑陋的循环

for i in range(0,5):
    plt.bar(0.5+i, frac[i], color=blue)
    plt.bar(0.5+i, 1-frac[i], bottom=frac[i], color=orange)

是的。你知道吗

plt.xticks([0.5, 1.5, 2.5, 3.5, 4.5], ['AR', 'BR', 'PE', 'RU', 'US'], 
rotation='horizontal')
plt.ylabel("Fraction")
plt.xlabel("")

plt.show()

It works, but i don't like it

我能不骑自行车吗?你知道吗

还有。当条形图标记为iy时,输出此图例 enter image description here


Tags: 数据inimportformatplotlibasbarplt
1条回答
网友
1楼 · 发布于 2024-03-28 09:04:10

如果我正确理解您的问题,您所说的“循环”通常称为循环(在本例中称为for循环)。你知道吗

你可以很容易地摆脱它。As per the documentation, ^{}接受标量(或向量)序列作为x=height=bottom=的输入。因此,您的代码可以简化为:

plt.bar(range(len(frac)), frac, bottom=0., color=blue, label="gmail")
plt.bar(range(len(frac)), 1-frac, bottom=frac, color=orange, label="hotmail")

为了使这一点开箱即用,我将您的frac列表转换为一个numpy数组,它允许您执行类似于“1-frac”的算术运算。你知道吗

完整代码:

frac = np.array([0.75, 0.6093, 0.7025, 0.0437, 0.1])
orange, blue = '#fd7f28', '#2678b2'

fig, ax = plt.subplots()
ax.bar(range(len(frac)), frac, bottom=0., color=blue, label="gmail")
ax.bar(range(len(frac)), 1-frac, bottom=frac, color=orange, label="hotmail")
ax.legend(loc=5, frameon=True)
ax.set_xticks(range(len(frac)))
ax.set_xticklabels(['AR', 'BR', 'PE', 'RU', 'US'])
plt.ylabel("Fraction")
plt.xlabel("")

enter image description here

相关问题 更多 >