Matplotlib Pie Chart Filter

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will demonstrate how to use filtering effects with Matplotlib's pie chart. We will use the pie chart drawing code borrowed from pie_demo.py and add filtering effects to the chart. The filtering effects are only effective if your SVG renderer supports it.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/SpecializedPlotsGroup(["`Specialized Plots`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/BasicConceptsGroup -.-> matplotlib/saving_figures("`Saving Figures to File`") matplotlib/SpecializedPlotsGroup -.-> matplotlib/pie_charts("`Pie Charts`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} matplotlib/importing_matplotlib -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} matplotlib/figures_axes -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} matplotlib/saving_figures -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} matplotlib/pie_charts -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/variables_data_types -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/for_loops -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/lists -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/tuples -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/sets -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/importing_modules -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/using_packages -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/standard_libraries -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/data_collections -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/data_visualization -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} python/build_in_functions -.-> lab-48975{{"`Matplotlib Pie Chart Filter`"}} end

Create a Pie Chart

We will create a square figure and axes for our pie chart. We will define the labels and fracs for the chart. We will also set the explode values for the chart slices. Finally, we will draw the pie chart with the defined parameters.

import matplotlib.pyplot as plt
from matplotlib.patches import Shadow

fig = plt.figure(figsize=(6, 6))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)

pies = ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%')

for w in pies[0]:
    w.set_gid(w.get_label())
    w.set_edgecolor("none")

for w in pies[0]:
    s = Shadow(w, -0.01, -0.01)
    s.set_gid(w.get_gid() + "_shadow")
    s.set_zorder(w.get_zorder() - 0.1)
    ax.add_patch(s)

plt.show()

Save the Chart as an SVG

We will save the pie chart as an SVG file using the io and xml.etree.ElementTree modules. We will define the filter definition for the shadow using a Gaussian blur and lighting effect. The lighting filter is copied from http://www.w3.org/TR/SVG/filters.html. We will test the filter using Inkscape and Firefox3, but note that Inkscape's exporting may not support it.

import io
import xml.etree.ElementTree as ET

f = io.BytesIO()
plt.savefig(f, format="svg")

filter_def = """
  <defs xmlns='http://www.w3.org/2000/svg'
        xmlns:xlink='http://www.w3.org/1999/xlink'>
    <filter id='dropshadow' height='1.2' width='1.2'>
      <feGaussianBlur result='blur' stdDeviation='2'/>
    </filter>

    <filter id='MyFilter' filterUnits='objectBoundingBox'
            x='0' y='0' width='1' height='1'>
      <feGaussianBlur in='SourceAlpha' stdDeviation='4%' result='blur'/>
      <feOffset in='blur' dx='4%' dy='4%' result='offsetBlur'/>
      <feSpecularLighting in='blur' surfaceScale='5' specularConstant='.75'
           specularExponent='20' lighting-color='#bbbbbb' result='specOut'>
        <fePointLight x='-5000%' y='-10000%' z='20000%'/>
      </feSpecularLighting>
      <feComposite in='specOut' in2='SourceAlpha'
                   operator='in' result='specOut'/>
      <feComposite in='SourceGraphic' in2='specOut' operator='arithmetic'
    k1='0' k2='1' k3='1' k4='0'/>
    </filter>
  </defs>
"""

tree, xmlid = ET.XMLID(f.getvalue())
tree.insert(0, ET.XML(filter_def))

for i, pie_name in enumerate(labels):
    pie = xmlid[pie_name]
    pie.set("filter", 'url(#MyFilter)')

    shadow = xmlid[pie_name + "_shadow"]
    shadow.set("filter", 'url(#dropshadow)')

fn = "svg_filter_pie.svg"
print(f"Saving '{fn}'")
ET.ElementTree(tree).write(fn)

View the Pie Chart with Filtering Effects

We will view the pie chart with the filtering effects applied. We will use Inkscape to open the SVG file and view the pie chart with the filtering effects.

Modify the Pie Chart with Different Filters

We can modify the pie chart with different filters by changing the filter definition. We can experiment with different filters to achieve different visual effects.

filter_def = """
  <defs xmlns='http://www.w3.org/2000/svg'
        xmlns:xlink='http://www.w3.org/1999/xlink'>
    <filter id='dropshadow' height='1.2' width='1.2'>
      <feGaussianBlur result='blur' stdDeviation='2'/>
    </filter>

    <filter id='MyFilter2' filterUnits='objectBoundingBox'
            x='0' y='0' width='1' height='1'>
      <feGaussianBlur in='SourceAlpha' stdDeviation='4%' result='blur'/>
      <feOffset in='blur' dx='4%' dy='4%' result='offsetBlur'/>
      <feSpecularLighting in='blur' surfaceScale='5' specularConstant='.75'
           specularExponent='20' lighting-color='#bbbbbb' result='specOut'>
        <fePointLight x='50%' y='50%' z='5000%'/>
      </feSpecularLighting>
      <feComposite in='specOut' in2='SourceAlpha'
                   operator='in' result='specOut'/>
      <feComposite in='SourceGraphic' in2='specOut' operator='arithmetic'
    k1='0' k2='1' k3='1' k4='0'/>
    </filter>
  </defs>
"""

tree, xmlid = ET.XMLID(f.getvalue())
tree.insert(0, ET.XML(filter_def))

for i, pie_name in enumerate(labels):
    pie = xmlid[pie_name]
    pie.set("filter", 'url(#MyFilter2)')

    shadow = xmlid[pie_name + "_shadow"]
    shadow.set("filter", 'url(#dropshadow)')

fn = "svg_filter_pie2.svg"
print(f"Saving '{fn}'")
ET.ElementTree(tree).write(fn)

Summary

In this lab, we learned how to use filtering effects with Matplotlib's pie chart. We created a pie chart, saved it as an SVG file, and applied filtering effects to the chart. We also modified the pie chart with different filters to achieve different visual effects.

Other Python Tutorials you may like