3

I am trying to add a horizontal bar at the bottom of each pie chart in a figure. I am using subplots to achieve this, but I don't know how to customise the subplots with the horizontal bars.

import matplotlib.pyplot as plt

fig, axes = plt.subplots(28, 11)

countery=0
for y in range(1,15):
    counterx=0
    
    for x in range(1,12):
        axes[countery,counterx].pie([70,20])

        axes[countery+1,counterx].barh('a',40,height=1)
        axes[countery+1,counterx].barh('a',60,left=40,height=1)
        axes[countery+1,counterx].axis('off')
        
        counterx=counterx+1

    countery=countery+2

plt.show()

enter image description here

I would like to change the size of the horizontal bar so it doesn't take all the horizontal space. and make it look smaller overall. I would like it to look something like this for each:

enter image description here

I've tried changing wspace and hspace in plt.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9, wspace=0.2, hspace=5) but no luck. Any help with this?

2 Answers 2

3

You can set the box_aspect of the bar charts. Also, using 14 rows with subgridspecs of 2 rows each is slightly faster than the 28 rows gridspec:

import matplotlib.pyplot as plt

fig = plt.figure()
gs = fig.add_gridspec(14, 11)

for y in range(gs.nrows):
    for x in range(gs.ncols):
        ax_pie, ax_bar = gs[y, x].subgridspec(2, 1, height_ratios=[5, 1]).subplots()
        ax_pie.pie([70,20])
        ax_bar.barh('a', 40, height=1)
        ax_bar.barh('a', 60, left=40, height=1)
        ax_bar.set_box_aspect(1/5)
        ax_bar.axis('off')

enter image description here

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

Comments

3

Tidied the loop a bit (removed the counters - you've used a for loop like a while loop - we can use the iterated variables directly). Other than that, the below should work. First, using figsize make the output taller than wide, as we expect each subplot to be taller than it is wide as per your goal image. Then set the ratios of the heights of each subplot by whether it is even (a pie) or odd (a bar). Fiddle with the 4 and 1 ratios in hr to get what looks right for you, and let me know if there's anything you don't understand.

import matplotlib.pyplot as plt

h = 14
w = 11

hr = [4 if i % 2 == 0 else 1 for i in range(h*2)]
fig, axes = plt.subplots(28, 11, figsize=(6, 12), gridspec_kw={'height_ratios':hr})

for y in range(0,h*2,2):
    for x in range(w):
        axes[y,x].pie([70,20])

        axes[y+1,x].barh('a',40,height=1)
        axes[y+1,x].barh('a',60,left=40,height=1)
        axes[y+1,x].axis('off')

plt.show()

Produces

enter image description here

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.