0

is it possible to get rid of the cycle?

Here is my input data

import matplotlib.pyplot as plt

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

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

Then this ugly cycle

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

Can I do it without a cycle?

Also. when bar is labelled iy outputs this legend enter image description here

1 Answer 1

1

If I understand your question correctly, what you call a "cycle" is commonly called a loop (or a for-loop in this case).

You can easily get rid of it. As per the documentation, bar() accepts sequences of scalars (or vectors) as inputs for x=, height= and bottom=. Your code can therefore be simplified as:

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")

for this to work out of the box, I transformed your frac list into a numpy array, which allows you to do arithmetics like "1-frac".

Full code:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.