Search code examples
pythonmatplotlibplotlabelpie-chart

Changing the label, and test colour in a pie chart


I have used this code:

winner_percent=games_df.winner.value_counts(normalize=True)*100
winner_percent.plot(
    kind='pie',
    title='Proportion of piece colour effect on the game result',
    autopct="%.1f%%",
    colors=['white','black','grey'],
    explode=(0, 0.08, 0),
    figsize=(10,7),
    wedgeprops={"edgecolor":"k",'linewidth': 2, 'linestyle': 'solid', 'antialiased': True},
    textprops={'color':"b"}

)
plt.legend()

And the graph that I got is:

enter image description here

Would you please guide me for achieving:

  • Changing the colour of the words White, Draw, and Black to Black colour.
  • Change the percentage number inside the white portion of the pie chart to black colour text, and the other two sections (black and grey), the percentage number becomes white colour.

Thank you in advance for your help.


Solution

  • Plot everything as black and change the two percentages manually as white:

    winner_percent= pd.Series({'white': 49.9, 'black': 45.4, 'draw': 4.7}, name='Winner')
    ax = winner_percent.plot(
            kind='pie',
            title='Proportion of piece colour effect on the game result',
            autopct="%.1f%%",
            colors=['white','black','grey'],
            explode=(0, 0.08, 0),
            figsize=(10,7),
            wedgeprops={"edgecolor":"k",'linewidth': 2, 'linestyle': 'solid', 'antialiased': True},
            textprops={'color':"k"}
    
        )
    
    ax.texts[3].set_color('w')
    ax.texts[5].set_color('w')
    plt.legend()
    

    output:

    matplotlib pie plot

    You can see the list of texts with:

    >>> ax.texts
    [Text(0.0034557017432522113, 1.099994571861817, 'white'),
     Text(0.001884928223592115, 0.5999970391973546, '49.9%'),
     Text(-0.17726600554646288, -1.1666090876028703, 'black'),
     Text(-0.10215329133185996, -0.6722832030253828, '45.4%'),
     Text(1.0880307327465517, -0.1618305428496183, 'draw'),
     Text(0.5934713087708463, -0.08827120519070088, '4.7%')]