Plotly Pie Charts: A Guide to Creating Impressive Data Visualizations
As artificial intelligence and machine learning continue to advance, data visualization becomes an increasingly critical skill. Being able to translate complex data, models, and results into compelling visual representations is key to driving insights, informing decisions, and communicating the value of AI/ML initiatives.
While there are many data visualization tools available, Plotly has emerged as a top choice thanks to its flexibility, interactivity, and ease of use. In fact, Plotly is now used by over 500,000 developers and data scientists across companies like Google, Nvidia, and Udemy [1].
In this guide, we‘ll dive into the world of Plotly with a focus on one of the most commonly used chart types – the pie chart. We‘ll cover the basics of creating pie charts in Plotly, share strategies and code samples for taking your charts to the next level through customization and creative enhancements, and explore pie chart best practices and real-world AI/ML use cases.
Why Plotly for AI/ML Data Visualization?
Plotly is an open-source data visualization library that allows you to create interactive, publication-quality graphs and dashboards in Python, R, JavaScript, and more. Its extensive capabilities and ease of use make it well-suited for AI/ML data visualization. Some key advantages include:
-
Wide range of chart types: Plotly offers over 40 different chart types, giving you the flexibility to choose optimal visualizations for AI/ML data like model performance metrics, feature importance, dataset distributions, and more.
-
Interactivity: The ability to zoom, pan, hover for details, and interact with visualizations is especially valuable in AI/ML for exploring high-dimensional data, analyzing results, and conveying complex relationships.
-
Aesthetic customization: From colors and fonts to layout and annotations, Plotly provides fine-grained control over the look and feel of your AI/ML visualizations.
-
Animation: Animated charts allow you to showcase how models, results, and datasets evolve throughout the ML workflow.
-
Easy integration: Plotly charts can be embedded in web-based AI/ML tools, reports, and dashboards or exported for presentations and sharing.
Creating a Basic Pie Chart
Pie charts are a popular choice for visualizing how a whole divides into distinct parts, clearly showing each category‘s proportions. They can be useful in AI/ML for displaying data like class distributions in a training set or relative feature importance.
Here‘s a basic code example of creating a pie chart in Plotly with Python:
import plotly.express as px
data = {‘Fruit‘: [‘Apples‘, ‘Oranges‘, ‘Bananas‘, ‘Berries‘],
‘Amount‘: [350, 450, 100, 250]}
df = pd.DataFrame(data)
fig = px.pie(df, values=‘Amount‘, names=‘Fruit‘, title=‘Fruit Distribution‘)
fig.show()
This code produces the following interactive pie chart:

Customizing Your Pie Chart
Plotly provides many options for customizing your pie charts to better convey your AI/ML data story:
Custom colors: Use color_discrete_sequence to set a color scheme tailored to your branding or use case:
fig = px.pie(df, values=‘Amount‘, names=‘Fruit‘,
color_discrete_sequence=[‘#636EFA‘, ‘#EF553B‘, ‘#00CC96‘, ‘#AB63FA‘],
title=‘Fruit Distribution‘)

Label formatting: Adjust label style and content with textinfo, textposition:
fig.update_traces(textinfo=‘percent+label‘, textposition=‘inside‘)

Legend styling: Control the legend‘s position and format:
fig.update_layout(legend=dict(orientation="h", y=1, x=0.5,
xanchor=‘center‘, yanchor=‘top‘))

Adding Images and Annotations
Overlaying images and annotations on pie charts can provide helpful context for AI/ML data. For example, you could use images to represent different types of models in a performance comparison chart.
Adding an image:
fig.add_layout_image(dict(source="https://i.imgur.com/iLwPzYW.png",
xref="paper", yref="paper",
x=0.5, y=0.5, sizex=0.4, sizey=0.4,
xanchor="center", yanchor="middle"))
Adding an annotation:
fig.add_annotation(dict(text=‘Based on Q3 2023 model evaluation‘,
x=0.5, y=1.08, xref=‘paper‘, yref=‘paper‘,
showarrow=False))

Animating Pie Charts
Animated charts are very effective at showing change over time, like how a model‘s predictions on different classes shift with each training epoch:
epochs_df = df.assign(epoch=df.index)
fig = px.pie(epochs_df, values=‘Amount‘, names=‘Fruit‘,
animation_frame=‘epoch‘,
color_discrete_sequence=[‘#636EFA‘, ‘#EF553B‘, ‘#00CC96‘, ‘#AB63FA‘])
fig.update_layout(title=‘Predicted Class Distribution Over Training Epochs‘)

Creating a Donut Chart
A donut chart is a pie chart with a center cutout, useful for focusing on the outer rim data or adding central summary stats/graphics.
fig = px.pie(df, values=‘Amount‘, names=‘Fruit‘, hole=.6,
color_discrete_sequence=[‘#636EFA‘, ‘#EF553B‘, ‘#00CC96‘, ‘#AB63FA‘])
fig.update_layout(annotations=[dict(text=‘2023 YTD‘, x=0.5, y=0.5,
font_size=20, showarrow=False)])

Combining Chart Types
Combining pie charts with other visualizations in a dashboard can give a more complete picture of complex AI/ML data.
Here‘s an example of displaying a pie chart alongside a bar chart:
from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2, specs=[[{"type": "pie"}, {"type": "bar"}]])
fig.add_trace(go.Pie(values=df[‘Amount‘], labels=df[‘Fruit‘]), row=1, col=1)
fig.add_trace(go.Bar(x=df[‘Fruit‘], y=df[‘Amount‘]), row=1, col=2)
fig.update_layout(title_text=‘Fruit Distribution‘)
Real-World AI/ML Examples
Model performance monitoring: A self-driving car company uses an animated donut chart on their ML monitoring dashboard to track the distribution of obstacle classes (pedestrians, vehicles, signs, etc.) detected in real-time by their perception models. The dashboard refreshes every minute to show the latest class breakdowns, with the model version displayed in the center of the donut. This allows engineers to easily spot if models start misclassifying or missing obstacles.
Displaying global AI adoption: An AI research firm publishes an annual report on worldwide AI adoption trends. This year‘s report features an interactive pie chart showing the breakdown of AI use cases across industries (e.g. healthcare, finance, retail, manufacturing). Hovering over each slice shows a description and representative company logos for that industry. Clicking a slice filters the rest of the report to focus on AI in that sector.
Comparing NLP model architectures: A natural language processing (NLP) research team is writing a blog post on the performance of different neural network architectures for text classification. They create a pie chart showing the relative numbers of parameters for each architecture (LSTM, CNN, Transformer, etc.). Architectures taking up more of the pie require more computational resources to train and run. The researchers use the chart to frame their discussion of the tradeoffs between model size and performance.
Accessibility Considerations
When creating pie charts (or any data visualizations), it‘s important to consider accessibility for users with visual impairments or other disabilities:
- Ensure sufficient color contrast between pie slices and background (a contrast ratio of at least 4.5:1 is recommended)
- Provide text alternatives for color-coded data, like labels or a legend
- Enable keyboard navigation for interacting with the chart
- Follow Web Content Accessibility Guidelines (WCAG) for any web-embedded charts
Plotly has specific documentation on optimizing charts for screen readers and other assistive technologies.
Integrating with AI/ML Dashboards
Pie charts are a valuable addition to AI/ML-powered analytics dashboards, providing high-level breakdowns and insights at a glance. Some tips for integration:
- Use consistent colors, fonts, and branding across all charts in the dashboard
- Include clear titles and labels to quickly convey the purpose of each chart
- Enable interactivity like linked filtering, where clicking on a pie slice updates other linked charts to show data for that slice
- Provide customization options so users can tailor pie charts to their specific needs and questions
Python libraries like Dash allow you to build complete web-based dashboards with Plotly charts and AI/ML-driven data and interactivity.
Automated Insights with AI/ML
In addition to visualizing the outputs of AI/ML models, you can also use AI/ML to automatically derive insights from your pie chart data. For example:
- Anomaly detection algorithms can identify unexpected changes or outliers in pie chart distributions, like a sudden drop in a usually dominant category
- Natural language generation models can produce automated text summaries of key pie chart takeaways
- Forecast models can predict future pie chart distributions based on historical patterns
By combining AI/ML-powered insights with effective pie chart visualizations, you can uncover and communicate meaningful data stories faster than ever before.
Pie Chart Best Practices
To make the most effective pie charts, keep these key best practices in mind:
-
Use for proportions, not absolute numbers: Pie charts are best for showing how a whole is divided into parts, not for comparing raw numbers or amounts [2].
-
Limit slices to 5-7: Too many tiny slices can be hard to read and compare. If needed, group smaller categories into an "Other" slice [3].
-
Order slices meaningfully: Start the most important slice at 12 o‘clock and arrange the rest in descending order, clockwise [4].
-
Avoid 3D and other distortions: 3D pie charts skew proportions and make interpretation more difficult. Stick to clear, 2D designs [5].
-
Highlight the key message: Use colors, annotations, and labels purposefully to draw attention to main takeaways or points of comparison.
Conclusion
In this guide, we‘ve walked through how Plotly can help you create impressive, insightful pie charts for your AI/ML data visualization needs. To recap, the key points are:
- Plotly‘s customizability, interactivity, and ease of use make it a top choice for AI/ML visualization
- Pie charts are an intuitive way to show data distributions and proportions
- Customizing colors, labels, and style helps tailor pie charts to your use case and audience
- Animations, images, and annotations add visual interest and context
- Pie charts pair well with other chart types for more comprehensive dashboards and data stories
- AI/ML-generated insights can further enhance pie chart storytelling
- Following pie chart best practices ensures your data and message come across clearly
We hope this guide has inspired you to level up your AI/ML pie charts with Plotly. Effective data visualization is a critical part of driving real-world AI/ML impact – so go forth and create some impressive, insightful pies!