pie chart python
Python hosting: Host, run, and code Python in the cloud!
Matplotlib is a versatile library in Python that supports the creation of a wide variety of charts, including pie charts. Check out the Matplotlib gallery to explore more chart types.
Related course: Data Visualization with Matplotlib and Python
Crafting a Pie Chart with Matplotlib
To begin with, ensure you’ve imported the required module using: import matplotlib.pyplot as plt. Once done, the plt.pie() method is readily available for creating your pie chart.
Here’s a simple example that demonstrates how to generate a pie chart:
import matplotlib.pyplot as plt |
With the above code, the result is a visually pleasing pie chart.
Matplotlib allows for extensive customization. You can determine slice sizes, which segments should stand out from the center (explode), their respective labels, and even their colors.
plt.pie(sizes, explode=explode, labels=labels, colors=colors, ...) |
Enhancing Your Pie Chart with a Legend
To make your pie chart even more informative, consider adding a legend using the plt.legend() function. This overlays a legend on your chart, providing clarity.
import matplotlib.pyplot as plt |
This code renders a pie chart that’s enriched with a legend.
Always remember, after setting up your plot, call the method .show() to ensure it gets displayed.
plt.show() |
For more examples and downloadable code, click here.
Leave a Reply: