How to set border for wedges in Matplotlib pie chart?
0 986
Introduction
Pie charts are a great way to represent proportional data, and Matplotlib in Python makes them easy to create and customize. One useful customization is setting borders (or edges) around the wedges to make each section stand out more clearly. This can be especially helpful when slices are similar in color or size. In this tutorial, we’ll see how to add and style borders around the wedges of a pie chart using Matplotlib.
Adding Borders to Pie Chart Wedges
The plt.pie() function in Matplotlib includes parameters that allow you to customize the appearance of wedges. To set borders, you can use the wedgeprops parameter, which accepts a dictionary of style properties.
import matplotlib.pyplot as plt
# Sample data
sizes = [25, 35, 20, 20]
labels = ['A', 'B', 'C', 'D']
# Plot with borders
plt.pie(sizes, labels=labels, wedgeprops={'edgecolor': 'black'})
plt.title('Pie Chart with Borders on Wedges')
plt.show()
In this example, wedgeprops={'edgecolor': 'black'} adds a black border to all slices, making them visually distinct.
Customizing Border Thickness
You can also control the width of the borders by adding the linewidth property inside wedgeprops. This allows for further customization depending on your chart’s design needs.
import matplotlib.pyplot as plt
sizes = [40, 30, 20, 10]
labels = ['X', 'Y', 'Z', 'W']
plt.pie(sizes, labels=labels, wedgeprops={'edgecolor': 'black', 'linewidth': 2})
plt.title('Pie Chart with Thicker Borders')
plt.show()
Here, the linewidth: 2 setting creates a thicker edge around each wedge, enhancing clarity.
Combining Border and Fill Styling
Borders can also be used alongside custom colors and transparency settings. This allows you to create more polished and informative visualizations.
import matplotlib.pyplot as plt
sizes = [30, 25, 25, 20]
labels = ['Red', 'Green', 'Blue', 'Yellow']
colors = ['red', 'green', 'blue', 'yellow']
plt.pie(
sizes,
labels=labels,
colors=colors,
wedgeprops={'edgecolor': 'white', 'linewidth': 1.5, 'linestyle': '--'},
startangle=90
)
plt.title('Styled Pie Chart with Colored Wedges and Borders')
plt.show()
In this example, we’ve added white dashed borders and applied specific colors to each wedge, resulting in a visually appealing pie chart.
Conclusion
Adding borders to wedges in a Matplotlib pie chart is a simple yet powerful way to improve readability and visual distinction. Using the wedgeprops parameter, you can customize edge color, thickness, and style to match the aesthetic and purpose of your chart. It’s a small detail that can make a big difference in how your data is perceived.
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments