PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 23, 2022

[FIXED] How to show all categories in legend in pie chart with matplotlib python

 April 23, 2022     matplotlib, pie-chart, python     No comments   

Issue

Hi I am trying a plot chart and have some difficulties to show the legend. Here's my code below:

age = ['below 20', '20-30', '30-40', '40-50']


age_count = [23,0,35,0]


labels = age
sizes = age_count

fig1, ax1 = plt.subplots()

ax1.pie(sizes, autopct='%1.1f%%',
        shadow=True, startangle=90)

ax1.legend(labels,bbox_to_anchor=(1, 0),loc='lower left')

I do not want to show the categories with zero count in the pie chart plot. Still I want to show all the category names (i.e. 20-30,40-50) in the legend. I tried the code above but it is now working. Would like to know where went wrong?


Solution

from matplotlib.pyplot.pie docs:

"autopct None or str or callable, default: None

If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt % pct. If it is a function, it will be called."

you can specify a specific bihavier by passing a function to autopct like so:

import matplotlib.pyplot as plt
age = ['below 20', '20-30', '30-40', '40-50']
age_count = [23,0,35,0]

def f(cpt):
    if cpt == 0:
        return ''
    else:
        return  '%.2f' %cpt

fig1, ax1 = plt.subplots()
ax1.pie(age_count, autopct=f,
        shadow=True, startangle=90)
ax1.legend(age,bbox_to_anchor=(1, 0),loc='lower left')

enter image description here



Answered By - Yohai Magan
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing