8000 Adding "pie of pie" and "bar of pie" functionality · Issue #11858 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content
Adding "pie of pie" and "bar of pie" functionality #11858
Closed
@pjk645-zz

Description

@pjk645-zz

Excel has a functionality where a wedge of a pie chart can be "exploded" out into another pie or bar chart to explain the distribution within the wedge's subgroup. I couldn't find any support for this so I hacked a solution as I don't like being out charted by Excel. Maybe you guys could use this to make a more elegant version as I'm mostly a coder and not a developer. The code and output is below. I'm running Python 3.6.5 (Anaconda 5.2 dist) and matplotlib 2.2.2 on a Windows 7 64 bit machine.

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np
import math

# style choice
plt.style.use('fivethirtyeight')

# make figure and assign axis objects
fig = plt.figure(figsize=(15,7.5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

# pie chart parameters
ratios = [.27, .56, .17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode=[0.1,0,0]
# rotate so that first wedge is split by the x-axis
angle = -180*ratios[0]
ax1.pie(ratios, autopct='%1.1f%%', startangle=angle,
        labels=labels,explode=explode )

# bar chart parameters

xpos = 0
bottom = 0
ratios = [.33, .54, .07, .06]
width = .2
colors = [[.1,.3,.5], [.1,.3,.3], [.1,.3,.7], [.1,.3,.9] ]

for j in range(len(ratios)):
    height = ratios[j]
    ax2.bar(xpos, height, width, bottom=bottom, color=colors[j])
    ypos = bottom + ax2.patches[j].get_height()/2
    bottom += height
    ax2.text(xpos,ypos, "%d%%" % (ax2.patches[j].get_height()*100), ha='center')

plt.title('Age of approvers')
plt.legend(('50-65', 'Over 65', '35-49', 'Under 35'))
plt.axis('off')
plt.xlim(-2.5*width, 2.5*width)


# use ConnectionPatch to draw lines between the two plots
# get the wedge data for the first group
theta1, theta2 = ax1.patches[0].theta1, ax1.patches[0].theta2
center, r = ax1.patches[0].center, ax1.patches[0].r
bar_height = sum([item.get_height() for item in ax2.patches])
x = r*np.cos(math.pi/180*theta2)+center[0]
y = np.sin(math.pi/180*theta2)+center[1]
con = ConnectionPatch(xyA=(-width/2,bar_height), xyB=(x,y), coordsA="data", coordsB="data",
                      axesA=ax2, axesB=ax1)
con.set_color([0,0,0])
con.set_linewidth(4)
ax2.add_artist(con)

x = r*np.cos(math.pi/180*theta1)+center[0]
y = np.sin(math.pi/180*theta1)+center[1]
con = ConnectionPatch(xyA=(-width/2,0), xyB=(x,y), coordsA="data", coordsB="data",
                      axesA=ax2, axesB=ax1)
con.set_color([0,0,0])
ax2.add_artist(con)
con.set_linewidth(4)

plt.show()

Output:
bar_of_pie_example

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0