Search code examples
pythonmatplotlibpie-chart

Override Matplotlib pie chart percentage labels to a specific value that doesn't sum to 100%


I have a pie chart given by the following code

import matplotlib.pyplot as plt

colorPalette=["#61412B","#DCC57D","#D57838","#FFCE33"]

fig, (ax1,ax2)=plt.subplots(1,2,figsize=(10,10))
labels=["Small","Mid","Large"]
values=[.258,.284,.458]
ax1.pie(values,labels=labels,explode=[0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')
labels=["Market Peg","Primary Peg (Passive)","Limit","MidPoint Peg"]
values=[.027,.09,.35,.534]
ax2.pie(values,labels=labels,explode=[0.01,0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')

enter image description here

I noticed that my input value of 53.4% on the second plot gets pushed to 53.3%. Is there a way to override this and still display 53.4, even though it adds to over 100%?


Solution

  • You can actually redefine the label to whatever you want:

    import matplotlib.pyplot as plt
    
    colorPalette=["#61412B","#DCC57D","#D57838","#FFCE33"]
    
    fig, (ax1,ax2)=plt.subplots(1,2,figsize=(10,10))
    labels=["Small","Mid","Large"]
    values=[.258,.284,.458]
    ax1.pie(values,labels=labels,explode=[0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')
    labels=["Market Peg","Primary Peg (Passive)","Limit","MidPoint Peg"]
    values=[.027,.09,.35,.534]
    l = ax2.pie(values,labels=labels,explode=[0.01,0.01,0.01,0.01],colors=colorPalette,autopct='%1.1f%%')
    
    # get the Text object and change the text
    l[2][-1].set_text('95.3%')
    

    output: fake proportions

    how it works

    pie returns a list with some elements of the graph: the wedges, the outside labels, and the inside labels (the ones we want).

    >>> l
    ([<matplotlib.patches.Wedge at 0x7f709a12e130>,
      <matplotlib.patches.Wedge at 0x7f709a12e850>,
      <matplotlib.patches.Wedge at 0x7f709a12eee0>,
      <matplotlib.patches.Wedge at 0x7f709a13a5b0>],
     [Text(1.1060171651625381, 0.09394695506413589, 'Market Peg'),
      Text(0.9985589871945, 0.4847473043690852, 'Primary Peg (Passive)'),
      Text(-0.2875697258635596, 1.0721024450894407, 'Limit'),
      Text(-0.11648807636083792, -1.1038707026032315, 'MidPoint Peg')],
     [Text(0.6078112349091426, 0.051628506837047644, '2.7%'),
      Text(0.5487576416113918, 0.2663926627613891, '9.0%'),
      Text(-0.1580338133124066, 0.5891734157698728, '35.0%'),
      Text(-0.064015969891992, -0.6066316473765505, '53.4%')])