How to Create Plotly Pie Chart in Python: Simple Guide
To create a pie chart in Python using
plotly, use plotly.express.pie() by passing your data and labels as arguments. This function quickly generates an interactive pie chart that you can display with fig.show().Syntax
The basic syntax to create a pie chart with Plotly Express is:
plotly.express.pie(data_frame, names, values): Creates the pie chart.data_frame: Your data source, usually a pandas DataFrame.names: The column or list that contains the labels for each slice.values: The column or list that contains the numeric values for each slice.fig.show(): Displays the interactive pie chart.
python
import plotly.express as px fig = px.pie(data_frame, names='label_column', values='value_column') fig.show()
Example
This example shows how to create a simple pie chart with labels and values using Plotly Express. It demonstrates how to visualize the distribution of fruit quantities.
python
import plotly.express as px # Sample data fruits = ['Apples', 'Oranges', 'Bananas', 'Grapes'] quantities = [30, 20, 40, 10] # Create pie chart fig = px.pie(names=fruits, values=quantities, title='Fruit Quantities') fig.show()
Output
An interactive pie chart window showing four slices labeled Apples, Oranges, Bananas, and Grapes with sizes proportional to 30, 20, 40, and 10 respectively.
Common Pitfalls
Common mistakes when creating Plotly pie charts include:
- Not passing
namesandvaluescorrectly, which causes errors or empty charts. - Using mismatched lengths for labels and values lists.
- Forgetting to call
fig.show(), so the chart does not display. - Passing data in unsupported formats instead of lists or DataFrame columns.
python
import plotly.express as px # Wrong: mismatched lengths fruits = ['Apples', 'Oranges'] quantities = [30, 20, 40] # Extra value # This will cause an error or unexpected behavior # fig = px.pie(names=fruits, values=quantities) # fig.show() # Correct way fruits = ['Apples', 'Oranges', 'Bananas'] quantities = [30, 20, 40] fig = px.pie(names=fruits, values=quantities) fig.show()
Quick Reference
Here is a quick summary of key parameters for px.pie():
| Parameter | Description |
|---|---|
| data_frame | Data source (pandas DataFrame) |
| names | Labels for pie slices (column name or list) |
| values | Numeric values for slices (column name or list) |
| title | Chart title (string) |
| color | Optional: color grouping |
| hole | Optional: size of hole for donut charts (0 to 1) |
Key Takeaways
Use plotly.express.pie() with names and values to create pie charts easily.
Always call fig.show() to display the chart.
Ensure labels and values have matching lengths to avoid errors.
You can customize the chart with parameters like title and hole for donut style.
Plotly pie charts are interactive and great for visualizing proportions.